Click here to Skip to main content
15,434,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
User table:
UserID (PK)
UserName
CompanyID (FK NOT NULL)

Company table:
CompanyID (PK)
CompanyName

entity framework model (v3.5) generated like :
C#
public class User
{
  public string UserID;
  public string UserName;
  public Company company;
}

public class Company
{
   public string CompanyID;
   public string CompanyName;
}


You can see that there is no CompanyID field within User class.Then how to add new user to the database.

What I have tried:

Company c = new Company();
c.CompanyID = "...";

User u = new User();
...
u.company = c;

DBContext.AddUsers(u);
DBContext.SaveChanges();

this will cause the EF to add a new company to the database first, which will end up with a duplicate key exception.

i tried to set up a "foreign key" property like versions of Entity Framework, but failed.
Posted
Updated 15-Oct-17 5:11am
v3
Comments
Richard Deeming 13-Oct-17 8:32am    
Select the existing company from the database, and set the user's company to that.
855 13-Oct-17 9:32am    
is that the only way to do that? i already have the CompanyGUID, i don't want to connect database to get Company object. i don't need that
Richard Deeming 13-Oct-17 9:36am     CRLF
In more recent versions of Entity Framework, you can set up a "foreign key" property which would let you do that. Entity Framework Relationships and Navigation Properties[^] You'd need to see if you can do that in the version you're using, or if you can update to a more recent version.
855 13-Oct-17 9:52am    
I tried that it doesn't work.
Richard Deeming 13-Oct-17 9:54am    
Then update your question to show what you've tried, and what went wrong.

1 solution

first create a userview model same as user table in database then add that userview model to your database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900