Question

I'm trying to seed some data into a Code First table, but I'm probably doing it wrong.

I am getting duplicate rows in the Department table when I try to add a Person.

Here is an example of what I am trying to do.


[Table Person]

int Id;
string Name;
Department Dept;

[Table Department]

int Id;
string DeparmentName;

In one method I seeded Department with several entries.

Then, in another method, I try to Add a Person, but because person has a Department object in it, IT adds a duplicate Deparment to the Department table.

The code below is not exactly what I have because I was trying to shorten it for this posting, but the idea is the same.

var dbContext = new Context();
// Get the Department for this user
var assignedDept = dbContext.Departments.FirstOrDefault(b => b.Id== 40);


var seededUser = new Person 
{
Department = assignedDept,
Name = "John Doe"
};


var db = new Context();
db.Person.Add(seededUser);
db.SaveChanges();
Was it helpful?

Solution

Theres a really easy fix here,

db.Person.AddOrUpdate(seededUser);

And give the row an actual id

eg

var seededUser = new Person 
{
    Id = 1,
    Department = assignedDept,
    Name = "John Doe"
};

heres a real life example

https://github.com/lukemcgregor/StaticVoid.Blog/blob/master/Blog/Data/Migrations/Configuration.cs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top