When I try to insert a entity into the database that has a association with another entity which is already in the database and has an id the entityframework the associated entity gets inserted too. This causes a duplicate entry for the associated entity.
Insert method in the Repository class
public T Insert(T entity)
{
DbSet.Add(entity);
Context.SaveChanges();
return entity;
}
Call of the insert method
this happens somewhere in my Code. I save it into my session variable.
using(var repository = new Repository<User>())
{
user = repository.GetById(id);
}
Then some other place:
Post post = new Post{ User = user, Content ="oO" };
using (var rep = new Repository<Post>())
{
rep.Insert(post);
}
I resolved the duplicate insert with this snippet below. This there a better way than to cast for every entitytype and reattach the assocated entites?
if (entity is Post)
{
Post post = (Post)(object)entity;
Context.Users.Attach(post.User);
}