且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架以一对一关联方式保存数据

更新时间:2022-12-26 21:56:29

您不会以错误的方式保存数据,但是由于定义了双向依赖关系,它根本无法工作.仅当与已经保存的用户相关时才可以保存团队,并且仅当与现有团队相关时才可以保存用户.您必须通过将外键属性标记为可空(例如, 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();