就我而言,这可能有些懒惰,但是我找不到一个简单的例子。

参考我最喜欢的电视节目《权力的游戏》,我的示例如下:

Table Throne (ThroneID)
Table King (ThroneID)


使用实体框架4,我有两个表,它们之间具有1:1的关系。在代码中,我想将国王与王座关联。王座可以关联0或1个国王。如果是1:Many,我有Add()方法来创建关联。 1:1用什么?

(好吧,我意识到我的例子不是最好的……但是在这个例子中,KingID与ThroneID相同,以强制执行1:1)

GameOfThronesContext context = new GameOfThronesContext();
Throne t = new Throne();
King k = new King();
t.Kings.Add(k);  // doesn't work because "Add" isn't available
context.Thrones.AddObject(t);

最佳答案

下面的解决方案,如果对于EF Code First 4.1,它显示了如何设计两个类以使其具有一对零/一的关系,结果将是:


王位{Id(PK),名称..}
国王{Id(PK,FK),名称..}




public class Throne { public int Id { get; set; } public string Name { get; set; } public virtual King King { get; set; } }

public class King
{
    public int Id { get; set; }
    public virtual Throne Throne { get; set; }
    public string Name { get; set; }
}




然后在上下文的OnModelCreating或配置类中定义该关系:

public class MyContext : DbContext
{
    public DbSet< Throne> Thrones { get; set; }
    public DbSet< King> Kings { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
//We define the key for the King table modelBuilder.Entity< King>().HasRequired(x => x.Throne); } }

然后,您可以:

 var throne = new Throne(){Name = "First Throne"};
 var king = new King() { Name = "First King" };
 throne.King = king;
 context.Thrones.Add(throne);
 context.SaveChanges();

关于c# - 使用ASP.Net和Entity Framework:以1:1关系添加子对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8844009/

10-13 08:20
查看更多