实体框架问题 - 添加实体 [英] Entity framework question - add entity
问题描述
用户表:
用户ID(PK)
用户名
CompanyID(FK非空)
公司表:
CompanyID(PK)
CompanyName
实体框架模型(v3.5)生成如:
public class 用户
{
public string UserID;
public string UserName;
public 公司公司;
}
public class 公司
{
public string CompanyID;
public string CompanyName;
}
您可以看到User class中没有CompanyID字段。然后如何将新用户添加到数据库。
我的尝试:
公司c =新公司();
c.CompanyID =...;
用户u =新用户();
...
u.company = c;
DBContext.AddUsers(u);
DBContext.SaveChanges();
这将导致EF首先向数据库添加新公司,最终会出现重复的密钥异常。
i尝试设置像Entity Framework一样的外键属性,但失败了。
< blockquote>首先创建一个与数据库中的用户表相同的用户视图模型,然后将该用户视图模型添加到数据库中。
User table:
UserID (PK)
UserName
CompanyID (FK NOT NULL)
Company table:
CompanyID (PK)
CompanyName
entity framework model (v3.5) generated like :
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.
first create a userview model same as user table in database then add that userview model to your database.
这篇关于实体框架问题 - 添加实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!