实体框架将记录与相关对象 [英] Entity Framework adding record with a related object
问题描述
我们必须使用EF增加了一个新的记录到数据库以下ADDUSER方式:
We have the following AddUser method which adds a new record to the database using EF:
public User AddUser(User user)
{
using (var context = DataObjectFactory.CreateContext())
{
var userEntity = Mapper.Map(user);
context.AddObject("UserEntities", userEntity);
context.SaveChanges();
return Mapper.Map(userEntity);
}
}
我们的用户类型是这样的:
Our User type is like this:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Customer Customer { get; set; }
}
我们有一个客户表和一个用户表和用户表,我们CUSTOMERID作为外键。
We have a Customer table and a User table and in User table we have customerid as a foreign key.
在我们的名字,姓氏和客户ID字段,用户表,我们得到的名字,姓氏和客户ID(用户的下拉列表)从用户的详细信息,创建客户ID的客户对象,我们从用户那里得到,并通过所有的这些在 ADDUSER
方法,但什么情况是,用户被插入到数据库中,也是一个新客户被插入到客户表(用新的客户ID),是停止该的有什么办法?
In the USER table we have Firstname, Lastname and CustomerId fields, we get the firstname, lastname and customerid (dropdown list of customers) details from the user, create the Customer object with customerid we get from the user and pass all of these to the AddUser
method, but what happens is that the User gets inserted into the database and also a new Customer is inserted into the Customer's table (with a new customerid), is there any way of stopping this?
感谢
推荐答案
您需要将 EntityState
客户的设置为不变
。
You need to set the EntityState
of the Customer to Unchanged
.
像
context.Entry<Customer>(customer).State = EntityState.Unchanged;
或
context.ObjectStateManager.ChangeObjectState(userEntity.Customer, EntityState.Unchanged);
(取决于你使用的是什么样的背景下)
(depending on what kind of context you are using)
请参阅 http://msdn.microsoft.com/en-us/data /jj592676.aspx
这篇关于实体框架将记录与相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!