Reputation: 807
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:
user.Company = company;
company.Workers.Add(user);
Which way is preferable?
Upvotes: 2
Views: 75
Reputation: 14640
If company
is already attached to the context.
Either
var company = db.Set<Company>().Find(companyId);
or
db.Set<Company>().Attach(company);
user.Company = 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);
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.
Upvotes: 2