使用实体框架代码优先,如何插入具有现有属性的对象
这是一个简单的例子。
我有一个 Customer
记录,定义如下:
public class Customer
{
[Key]
public string Id { get;}
public UsState UsState { get; set; }
}
public class UsState
{
[Key]
public string StateAbbreviation {get;set;}
public string StateName {get;set;}
}
我已经在 UsState 中填充了 50 个州,现在我想插入一个与现有州相关的 Customer
记录。
如果我说这样的话:
Customer customer = new Customer()
{
UsState = "CA",
Id = 1001
}
dbContext.Customers.add(customer);
我收到一条错误消息,指出状态正在尝试再次插入。
我怎样才能让添加使用现有状态而不是尝试重新插入它。我真正的问题有很多可能存在的嵌套对象,所以我需要一般性地解决这个问题。
谢谢
Here is the simple case.
I have a Customer
record defined like this:
public class Customer
{
[Key]
public string Id { get;}
public UsState UsState { get; set; }
}
public class UsState
{
[Key]
public string StateAbbreviation {get;set;}
public string StateName {get;set;}
}
I already have my UsState's populated with the 50 states, now I want to insert one Customer
record that ties to an existing state.
If I say something like:
Customer customer = new Customer()
{
UsState = "CA",
Id = 1001
}
dbContext.Customers.add(customer);
I get an error saying state is trying to be inserted again.
How can I get the add to use an existing state and not try and re-insert it. My real problem has lots of nested objects that may exist so I need to solve this in general.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道的两种方法是:
将 EntityState 设置为适合您的操作的内容或
从数据库获取 UsState 并将其添加到客户之前保存,这将给它一个 UnModified 的 EntityState 或类似的东西。
要更改 EntityState,您需要访问 DbContext 的 ObjectContext,如以下线程所示: 实体框架代码优先 - DbContext 上没有 Detach() 方法
Two ways I know is:
Set EntityState to what is appropriate for your action or
Get the UsState from the database and add it to the customer right before saving, which will give it an EntityState of UnModified or something like that.
to change the EntityState you need to get to the ObjectContext of your DbContext like shown in this thread: Entity Framework Code First - No Detach() method on DbContext
如果您从表数据的角度考虑这一点,那么您的客户表中应该有一列描述客户的状态。您还有一个状态表,可用于连接在一起以获取状态名称。
“状态”列只是一个代表状态的字符串。因此,您的类应该以相同的方式定义,使用 ID 和 State,并且如果您想包含 USState 类的信息,请定义一个 UsState 类型的属性,并定义一个foreignkey:
然后,当您创建一条新记录时,设置字符串的文本,而不是 UsState 对象。
If you think about this in terms of table data, your Customer table should have a column in it that describes the customer's state. You also have a state table that you can use to join together to get the state name.
The "state" column is a just a string representing the state. So your class should be defined the same way, with and ID and a State, and if you want to include the information for your USState class, defined a property of type UsState with a ForeignKey defined:
Then, when you create a new record, set the text of the string, not the UsState object.