Reputation: 15
I have a strange problem with EntityFraemwork when I want to update entity. I have User entity and Searchfilter entity, they have one-to-many relationship
public class User : IdentityUser
{
public virtual List<SearchFilter> SearchFilters { get; set; }
}
public class SearchFilter : BaseEntity, IAggregateRoot
{
public virtual User User { get; set; }
}
1 - I create user 2 - I run method that creates and adds user to searchfilter
SearchFilter searchFilter = SearchFilterRepository.AddAsync(new SearchFilter
{
SearchInDescription = false,
SearchInTitle = false
}).Result;
I used Result without async that had a test. I thought the problem was in async operations in EF. Then:
searchFilter.User = user;
SearchFilterRepository.Update(searchFilter);
Update:
public void Update(T entity)
{
_dbMainContext.Entry(entity).State = EntityState.Modified;
_dbMainContext.SaveChanges();
}
And I have an error: The "PK_AspNetUsers" PRIMARY KEY constraint was violated. Unable to insert duplicate key into dbo.AspNetUsers object. Duplicate key value: (0e535b73-7cff-4152-9157-214b9821d264). The execution of this instruction has been interrupted.
I think that EF, update SearchFilter and ADD new user, which already exists, how can i avoid this?
Upvotes: 0
Views: 57
Reputation: 490
add UserId property and use it instead of reference User Property
public class SearchFilter : BaseEntity, IAggregateRoot
{
public Guid UserId { get; set; }
public virtual User User { get; set; }
}
then use insert or update
searchFilter.UserId = /* Add User Guid */;
SearchFilterRepository.Update(searchFilter);
Upvotes: 1