c#-HasRequired和WithOptional不生成一对一关系
作者:互联网
我有两个非常简单的对象:
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());
我看到,尽管我没有将用户分配给GenericObject,但变量u实际上是GenericObjects指向我在数据库中创建的用户.
解决方法:
您应该阅读: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.
在简单的情况下,一个新用户和一个新GenericObject EF可以推断处于相同状态的两个实体之间可能的唯一关系.在其他情况下,他会抛出.
标签:fluent,entity-framework-6,visual-studio-2017,c,entity-framework 来源: https://codeday.me/bug/20191211/2105703.html