C# 如何使用 EF 4.3 中的复杂键使用 AddOrUpdate 播种数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10234912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to seed data with AddOrUpdate with a complex key in EF 4.3
提问by Keith Sirmons
I am trying to seed a development database with some test data.
我正在尝试使用一些测试数据为开发数据库提供种子。
I have used context.People.AddOrUpdate(p => p.Id, people));with much success.
我已经使用context.People.AddOrUpdate(p => p.Id, people));了很多成功。
I have another table that I need to seed, in which I would not know the primary key.
我有另一个需要播种的表,我不知道其中的主键。
For example, I would want to AddOrUpdate based on the First and Last names matching.
例如,我想根据名字和姓氏匹配来添加或更新。
I am unsure how to write the Expression correctly.
我不确定如何正确编写表达式。
context.People.AddOrUpdate(p => p.FirstName && p.LastName, people);
is obviously incorrect, but I hope it conveys the solution I am looking for.
显然不正确,但我希望它传达了我正在寻找的解决方案。
采纳答案by Ladislav Mrnka
Try this:
尝试这个:
context.People.AddOrUpdate(p => new { p.FirstName, p.LastName }, people);
回答by lukyer
If you got Only primitive types or enumeration types are supported in this context.because of using navigation property - consider adding foreign key property directly to the entity (maybe only with getter) and use it as Ladislav Mrnkaproposed.
如果您Only primitive types or enumeration types are supported in this context.因为使用导航属性而获得 - 考虑将外键属性直接添加到实体(可能仅使用 getter)并按照Ladislav Mrnka 的建议使用它。

