问题描述
我正在尝试使用外键关联在EF中实现一对一关联的方法.在我的情况下,用户和团队之间存在关联,并且我需要在每个用户中都有一个导航属性.尝试保存数据时遇到了问题.
I'm trying to use the foreign key association approach to achieve a one-to-one association in EF. In my case there's an association between a User and a Team, and I need a navigation property in each of them.I bumped into a problem when trying to save data.
这是模型的样子:
public class Team
{
public int ID { get; set; }
public string Name { get; set; }
public int OwnerID { get; set; }
public virtual User Owner { get; set; }
}
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public int TeamID { get; set; }
public virtual Team Team { get; set; }
}
按照上面引用的博客文章的说明,我将这些位添加到了 DbContext
OnModelCreating()
中:
I added these bits to the DbContext
OnModelCreating()
, as instructed in the blog post referenced above:
modelBuilder.Entity<User>()
.HasRequired(u => u.Team)
.WithMany()
.HasForeignKey(u => u.TeamID);
modelBuilder.Entity<Team>()
.HasRequired(t => t.Owner)
.WithMany()
.HasForeignKey(t => t.OwnerID)
.WillCascadeOnDelete(false);
现在,当添加这样的数据时:
And now when adding data like this:
User u = new User();
u.UserName = "farinha";
Team t = new Team("Flour Power");
u.Team = t;
t.Owner = u;
context.Users.Add(u);
context.Teams.Add(t);
context.SaveChanges();
甚至是这样:
User u = new User();
u.UserName = "farinha";
u.Team = new Team("Flour Power");
context.Users.Add(u);
context.SaveChanges();
我遇到以下错误:
关于如何解决此问题的任何想法?我是否以错误的方式保存数据?
Any idea of how to solve this? Am I saving the data in a wrong way?
预先感谢
推荐答案
您不会以错误的方式保存数据,但是由于定义了双向依赖关系,它根本无法工作.仅当与已经保存的用户相关时才可以保存团队,并且仅当与现有团队相关时才可以保存用户.您必须通过将外键属性标记为可空(例如, User
中的 TeamId
)来使一种关系成为可选关系:
You are not saving data wrong way but it simply cannot work because you defined bidirectional dependency. Team can be saved only if related to already saved user and user can be saved only if related to existing team. You must make one relation optional by marking foreign key property nullable (for example TeamId
in User
):
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public int? TeamID { get; set; }
public virtual Team Team { get; set; }
}
然后,您必须先保存 User
实体,然后才能保存 Team
.
Then you must save the User
entity first and then you can save Team
.
User u = new User();
u.UserName = "farinha";
context.Users.Add(u);
context.SaveChanges();
u.Team = new Team { Name = "Flour Power", OwnerID = u.ID };
context.SaveChanges();
这篇关于实体框架以一对一关联方式保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!