gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:38:22 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com