106

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.

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.

2 Answers 2

210

Try this:

context.People.AddOrUpdate(p => new { p.FirstName, p.LastName }, people);
7
  • 12
    @LadislavMrnka what if the identifier needs to be a complex type i.e. context.People.AddOrUpdate(p => new { p.Name.FirstName, p.Name.LastName }, people)?
    – gabe
    Feb 11, 2014 at 19:21
  • 3
    @LadislavMrnka, also, what if the property is a nullable type? i.e. context.People.AddOrUpdate(p => new { p.Birthdate }, people) ?
    – stack247
    Aug 1, 2014 at 23:44
  • 2
    Something to note here is that the 'people' collection needs to be an ARRAY and not a list. If you have a list of entities, you can simply call .ToArray() on the list. I struggled with that one :) - Good answer Sep 21, 2015 at 8:48
  • 1
    can't get this to work. possibly because (in addition to 3 properties specified in composite key) i have a another ID field with auto generated numbers?
    – Sonic Soul
    Mar 22, 2017 at 12:01
  • @LadislavMrnka is need to keep Migration folder(Configuration.cs and...) after do migration and update database fields???
    – AminM
    Oct 24, 2017 at 15:14
1

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 Mrnka proposed.

2
  • How to add navigation property of other table foreign key in code first approach? I have structure like context.People.AddOrUpdate(p => new { p.Name.FirstName, p.Name.LastName }, people) ? It this possible Dec 11, 2019 at 6:42
  • If I set getter property error is The specified type member 'NameId' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. Dec 11, 2019 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.