c# - 使用 ASP.Net 和 Entity Framework : adding a child object in a 1:1 relationship

标签 c# asp.net entity-framework entity-framework-4

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

引用我最喜欢的电视剧权力的游戏,我的例子如下:

Table Throne (ThroneID)
Table King (ThroneID)

使用 Entity Framework 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), Name..}
  • 国王{Id(PK,FK), Name..}

<p></p>

<p>public class Throne
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual King King { get; set; }
    }</p>

<pre><code>public class King
{
    public int Id { get; set; }
    public virtual Throne Throne { get; set; }
    public string Name { get; set; }
}
</code></pre>

<p></p>

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


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

<p></p>
然后你可以:

 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 : adding a child object in a 1:1 relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844009/

相关文章:

c# - 如何模拟网络浏览器以便网站为我提供正确的 HTML 源代码?

c# - 如何检索保存在 mysql 中的 asp.net 中的路径作为链接?

c# - 字符串拆分 ASP.NET/C#

entity-framework - Visual Studio 2013 和 Entity Framework

c# - 使用 TLS 1.2 从 HttpClient 连接到 Azure FrontDoor 后面的 API

C# - 为什么 System.IO.File.GetLastAccessTime 在找不到文件时返回预期值?

c# - 使用 C# 驱动程序的 MongoDB 更新数组

javascript - CSS 和 JScript 的谷歌浏览器问题

entity-framework - Entity Framework 预测

.net - Entity Framework 和可为空的字段