多对多的目标对象在C#中关系

多对多的目标对象在C#中关系

本文介绍了多对多的目标对象在C#中关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个小的教育项目工作行使perst.net。

I am working on a small educational project to exercise perst.net.

我们有一个微小的设计问题,那就是如何以最佳方式解决两个类之间的关系对象,即参与者的和的冠军的。这是一个多对多的关系作为的参与者的可以在很多的冠军参加的和的锦标赛的可以有多重的参与者

We have a tiny design problem, that is how to best resolve the relation between two classes of objects, that is the participant and championship. It is a many to many relation as participant can take part in many championships and championships can have a multiple participants.

请告知如何做到这一点最好在C#中,我应该使用'关系数据库一样的技术类?

Please advise how to do this best in C#, should I use the 'relational DB like' technical class?

推荐答案

如果你正在寻找一种面向对象(或领域驱动设计)的方法,然后第三个对象来处理的加入是完全错误的方式去了解这一点。您可以使用ILists /可枚举与添加...方法来处理这个如下:

If you're looking for an object oriented (or domain driven design) approach then a third object to handle the 'join' is entirely the wrong way to go about this. You can use ILists / Enumerables with Add... methods to handle this as follows:

public class Participant
{
    private readonly IList<Championship> _championships = new List<Championship>();

    public IEnumerable<Championship> Championships
    {
    	get { return _championships; }
    }

    internal void AddChampionship(Championship championship)
    {
    	if (!_championships.Contains(championship))
    		_championships.Add(championship);
    }
}

public class Championship
{
    private readonly IList<Participant> _participants = new List<Participant>();

    public IEnumerable<Participant> Participants
    {
    	get { return _participants; }
    }

    public void AddParticipant(Participant participant)
    {
    	if (_participants.Contains(participant)) return;
    	_participants.Add(participant);
    	participant.AddChampionship(this);
    }
}



这里的关键是要确保您管理的关系从一个侧面唯一的 - 如在这种情况下,这将是通过调用championship.AddParticipant()

The key here is to make sure you manage the relationship from one side only - e.g. in this case that would be by calling championship.AddParticipant()

这篇关于多对多的目标对象在C#中关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:56