4

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.

SventoryMang
  • 10,275
  • 15
  • 70
  • 113
  • After attaching your entity to the context you should set it's status to added or modified. See ObjectStateManager.ChangeObjectState method. But can't say why your Exists method gives you true before you save the user. – ElDog Jan 24 '12 at 16:07
  • @ElDog I tried that (you can see it commented out in the update) and it threw an error saying can't do that because the entity was either modified or deleted in between operations or something to that effect. – SventoryMang Jan 24 '12 at 16:11

1 Answers1

1

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.

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Is there no other way to generically do this? Yeah I posted this exact question here:http://stackoverflow.com/questions/8948815/entity-framework-generic-compare-type-without-id and tried the answer, which doesn't appear to be working. – SventoryMang Jan 24 '12 at 16:10
  • The problem is that some entities have an int ID with prop name being classnameId, while others are guids with prop name Id. To use any ID in the generic method they would have to implement the same base class/interface, but how could make an interface that covers both? – SventoryMang Jan 24 '12 at 16:18
  • Hmm Okay, I will see if I can use that to get something working. – SventoryMang Jan 24 '12 at 16:20
  • Actually I don't think this will work either because the objects that have GUID properties as ID as set upon creation. Is there a way to do a full object comparer in a LINQ query to say something like .Where(x => x.Equals(entity), except equals obviously won't work but is there something like that to do it generically? – SventoryMang Jan 24 '12 at 16:37
  • I fixed this problem, but now ran into another one. I will post a new question though since this one is long enough and I did solve the original problem. – SventoryMang Jan 24 '12 at 17:02
  • can you edit your answer to include the linked question? Your original answer doesn't really fit as I am not checking if ID is set. – SventoryMang Jan 24 '12 at 19:16
  • @DOTang: Done. I also removed my comment about it for the sake of cleanliness. – StriplingWarrior Jan 24 '12 at 21:25