c# - HasRequired 和 WithOptional 不生成一对一关系

标签 c# entity-framework visual-studio-2017 entity-framework-6 fluent

我有两个非常简单的对象:

public class GenericObject
{
    public int Id { get; set; }
    public string description { get; set; }
    public User UserWhoGeneratedThisObject { get; set; }
}

public class User
{
    public int Id { get; set; }  
    public string Name { get; set; }
    public string Lastname { get; set; }
}

我正在覆盖 OnModelCreating 函数来声明对象的关系:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GenericObject>().HasRequired(u => u.UserWhoGeneratedThisObject)
                                   .WithOptional();
    }

然后,在我的应用程序中,我执行以下操作:

using (var ctx = new TestContext())
{
    GenericObject myObject = new GenericObject();
    myObject.description = "testobjectdescription";
    User usr = new User() { Name = "Test"};
    ctx.Users.Add(usr);
    //myObject.UserWhoGeneratedThisObject = usr;
    ctx.GenericObjects.Add(myObject);
    ctx.SaveChanges();
}

当我将 myObject 添加到数据库时,我不应该遇到异常吗,因为我没有为它分配一个 User 对象? (注释掉的行)我希望在这种情况下看到异常,但代码工作正常。更糟糕的是,如果我在 ctx.SaveChanges() 之后添加以下两行:

var u = ctx.GenericObjects.Find(1);
System.Console.WriteLine(u.ToString());

我看到作为 GenericObjects 的变量 u 实际上指向我在数据库中创建的用户,即使我没有将用户分配给 GenericObject。

最佳答案

你应该阅读:Difference between .WithMany() and .WithOptional()?

代码:

using (var ctx = new Tests6Context()) {
    GenericObject myObject = new GenericObject();
    myObject.description = "testobjectdescription";
    User usr = new User() { Name = "Test" };
    ctx.Users.Add(usr);
    //myObject.UserWhoGeneratedThisObject = usr;
    ctx.GenericObjects.Add(myObject);


    myObject = new GenericObject();
    myObject.description = "testobjectdescription 2";
    usr = new User() { Name = "Test 2" };
    ctx.Users.Add(usr);
    //myObject.UserWhoGeneratedThisObject = usr;
    ctx.GenericObjects.Add(myObject);

    ctx.SaveChanges();
}

抛出:

System.Data.Entity.Infrastructure.DbUpdateException: Unable to determine the principal end of the 'ef6tests.GenericObject_UserWhoGeneratedThisObject' relationship. Multiple added entities may have the same primary key.

在简单的情况下,一个新的用户和一个新的通用对象 EF 推断出处于相同状态的两个实体之间唯一可能的关系。在其他情况下,他会抛出。

关于c# - HasRequired 和 WithOptional 不生成一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55164487/

相关文章:

visual-studio - VS2017 空白登录屏幕

c# - Azure 表存储 - 扩展 ITableEntity 的任何类型的通用下载

c# - 使用 MVVM 处理用户设置

c++ - unordered_set 通过 lambdas 自定义哈希

c# - LINQ to EF4 日期时间比较问题

c# - 如何从 SQL 查询返回动态对象

c# - 如何在 Visual Studio 2017 中使用 SQLite?

c# - GC.SuppressFinalize 是否保持对象的根

c# - 如何将重复键添加到字典 <string,string>

c# - 上下文在代码优先模式下使用,代码是从 EDMX 文件生成的,用于数据库优先或模型优先开发