简体   繁体   English

实体框架一对多问题

[英]Entity Framework One-To-Many issue

I use Entity Framework in my project. 我在项目中使用实体框架。 I stuck in some trouble. 我陷入了麻烦。

I have two classes. 我有两节课。 Here are they: 他们是:

public class User
{
    public virtual Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual string Username { get; set; }
    public string Email { get; set; }
    public virtual Company Company { get; set; }
}

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Requisites { get; set; }
    public virtual List<User> Workers { get; set; }
}

Also I have repo. 我也有回购。 So when I create a new user and I want to add this user to company. 因此,当我创建一个新用户时,我想将此用户添加到公司中。 How should I implement that? 我应该如何实施? I have two ways: 我有两种方法:

  1. user.Company = company;
  2. company.Workers.Add(user);

Which way is preferable? 哪种方法更好?

If company is already attached to the context. company是否已附加到上下文。

Either

var company = db.Set<Company>().Find(companyId);

or 要么

db.Set<Company>().Attach(company);

user.Company = company; user.Company =公司;

In the first case, if you only do that. 在第一种情况下,如果仅这样做。 The user will not be added to the database, you need to have this too. 该用户将不会被添加到数据库,您也需要具有此权限。

db.Entry(user).State = EntityState.Added;

or 要么

db.Set<User>().Add(user);

Then user will be added and will have relationship with company. 然后,将添加用户并与公司建立关系。

company.Workers.Add(user); company.Workers.Add(用户);

This one only should be okay, the user will be added and have relationship with company. 这一项应该没问题,用户将被添加并与公司建立关系。 But be careful if Workers is null, you need to instantiate it first. 但是请注意,如果Workers为null,则需要首先实例化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM