实体框架代码优先设计
本文关键字:框架 代码 实体 | 更新日期: 2023-09-27 18:10:06
我正在为使用实体框架6的议员目录做设计,并且在如何构建我的实体的一些指导之后。我已经有一段时间没有做任何从头开始这样的事情了,任何帮助都会非常感激。我更习惯先做这个数据库,而不是先写代码,这需要一段时间来改变我对事情的看法。
我有两个实体:
public class Councillor
{
[Key]
public int CouncillorId { get; set; }
public string Name { get; set; }
public ICollection<Committee> Committees { get; set; }
}
public class Committee
{
[Key]
public int CommitteeId { get; set; }
public string CommitteeName { get; set; }
public ICollection<Councillor> Councillors { get; set; }
}
存在多对多关系,即一个议员可以在多个委员会中任职,而一个委员会有多个议员。
除此之外,委员会还有担任主席、副主席或仅担任委员的议员。列表处理后,但我正在寻找建议(最佳实践)设置其他位置。
我现在想的是:
public class Committee
{
[Key]
public int CommitteeId { get; set; }
public string CommitteeName { get; set; }
public int ChairmanId { get; set; } // link to councillor entity
public int ViceChairId { get; set; } // link to councillor entity
public ICollection<Councillor> Councillors { get; set; }
}
对于这种方法有什么建议或问题吗?首先,在数据库中,我可能只有一个链接表,用于委员会成员的councilorid, CommitteeId和Position。但是我不知道怎么把它翻译成代码
听起来您只需要添加一个连接表来将您的议员加入委员会。我将保留委员会对象上的主席和副主席属性。
public class Councillor
{
[Key]
public int CouncillorId { get; set; }
public string Name { get; set; }
// Junction Table Navigation Property
[ForeignKey("CouncillorId")]
public virtual ICollection<CouncillorCommittee> CouncilorCommittees { get; set; }
}
public class Committee
{
[Key]
public int CommitteeId { get; set; }
public string Name { get; set; }
public int ChairmanId { get; set; }
public int ViceChairmanId { get; set; }
[ForeignKey("ChairmanId")]
public virtual Councillor Chairman { get; set; }
[ForeignKey("ViceChairmanId")]
public virtual Councillor ViceChairman { get; set; }
// Junction Table Navigation Property
[ForeignKey("CommitteeId")]
public virtual ICollection<CouncillorCommittee> CouncilorCommittees { get; set; }
}
// Represents the joining table
public class CouncillorCommittee
{
[Key]
public int CouncillorCommitteeId { get; set; }
public int CouncillorId { get; set; }
public int CommitteeId { get; set; }
[ForeignKey("CouncillorId")]
public virtual Councillor Councillor { get; set; }
[ForeignKey("CommitteeId")]
public virtual Committee Committee { get; set; }
}
在你的代码中,你会像这样得到委员会和委员的列表:
var committees = from c
in Committees
select new
{
CommitteeName = c.Name,
Chairman = c.Chairman,
ViceChairman = c.ViceChairman,
Councillors = from cc
in c.CouncilorCommittees
select cc.Councillor
}
同样,要获得所有的议员和他们所属的委员会,您可以这样做:
var councillors = from c
in Councillors
select new
{
CouncillorName = c.Name,
Committes = from cc
in c.CouncilorCommittees
select cc.Committee
}