Reputation: 10479
EDIT: ANSWER AT BOTTOM OF THIS QUESTION
Okay so I've got some generic EF functions (most of which I have gotten from here) but they don't seem to work.
I've got 3 classes:
public class Group : Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual GroupType GroupType { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class GroupType: Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class User: Entity
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
My CRUD Operations:
public void Insert(TClass entity)
{
if (_context.Entry(entity).State == EntityState.Detached)
{
_context.Set<TClass>().Attach(entity);
}
_context.Set<TClass>().Add(entity);
_context.SaveChanges();
}
public void Update(TClass entity)
{
DbEntityEntry<TClass> oldEntry = _context.Entry(entity);
if (oldEntry.State == EntityState.Detached)
{
_context.Set<TClass>().Attach(oldEntry.Entity);
}
oldEntry.CurrentValues.SetValues(entity);
//oldEntry.State = EntityState.Modified;
_context.SaveChanges();
}
public bool Exists(TClass entity)
{
bool exists = false;
if(entity != null)
{
DbEntityEntry<TClass> entry = _repository.GetDbEntry(entity);
exists = entry != null;
}
return exists;
}
public void Save(TClass entity)
{
if (entity != null)
{
if (Exists(entity))
_repository.Update(entity);
else
_repository.Insert(entity);
}
}
Finally I am calling this code in the following method:
public string TestCRUD()
{
UserService userService = UserServiceFactory.GetService();
User user = new User("Test", "Test", "Test", "TestUser") { Groups = new Collection<Group>() };
userService.Save(user);
User testUser = userService.GetOne(x => x.UserName == "TestUser");
GroupTypeService groupTypeService = GroupTypeServiceFactory.GetService();
GroupType groupType = new GroupType("TestGroupType2", null);
groupTypeService.Save(groupType);
GroupService groupService = GroupServiceFactory.GetService();
Group group = new Group("TestGroup2", null) { GroupType = groupType };
groupService.Save(group);
user.Groups.Add(group);
userService.Save(user);
return output;
}
When I get to:
user.Groups.Add(group);
userService.Save(user);
I get the following error:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
With the following inner exception:
The INSERT statement conflicted with the FOREIGN KEY constraint "User_Groups_Source". The conflict occurred in database "DBNAME", table "dbo.Users", column 'Id'.
The Problems:
1) Exists
always returns true even if the entity was just created in memory and therefore insert is never actually being called only Update
inside the Save
method, I guess this is because I don't understand DbEntityEntry fully because both itself and Entry.Entity are never null. How can I check for an exists?
2) Even though all the code runs in TestCRUD until the very end, none of those entities are actually being saved to the database. I am positive I have my database set-up correctly because my custom Initializer is dropping and recreating the database always and inserting seed data every time. This is probably because update is always being called as mentioned in number 1.
Any ideas how to fix?
EDIT: ANSWER
As assumed, the problem was Exists
was always returning true so insert was never being called. I fixed this by using reflection to get the primary key and inserting that into the find method to get exists like so:
public bool Exists(TClass entity)
{
bool exists = false;
PropertyInfo info = entity.GetType().GetProperty(GetKeyName());
if (_context.Set<TClass>().Find(info.GetValue(entity, null)) != null)
exists = true;
return exists;
}
All the other methods started working as expected. However, I got a different error on the same line:
user.Groups.Add(group);
userService.Save(user);
which was:
Violation of PRIMARY KEY constraint 'PK_GroupTypes_00551192'. Cannot insert duplicate key in object 'dbo.GroupTypes'. The statement has been terminated.
I'll be posting that as a new question since it's a new error, but it did solve the first problem.
Upvotes: 4
Views: 2067
Reputation: 156459
How can I check for an exists?
The way I've typically seen people checking whether an entity already exists is by checking whether its Id
property is greater than zero. You should be able to either use an interface with the Id
property on it or (if you expect to have Entities with multiple key properties) you could have each entity override an abstract base class, overriding an Exists
property to check its own ID properties for non-default values. Or you could use reflection to find the ID property or properties automatically, as explained here.
I suspect the rest of the issues will go away once you are correctly inserting new items rather than trying to update them.
Upvotes: 1