问题描述:

So with entity framework I'm trying to update two existing entities.

There I've the main object something like:

public class MainObject

{

public string Name { get; set; }

public virtual SmallObject Part { get; set;}

}

public class SmallObject

{

public string Name { get; set; }

}

In the repository I first check if the SmallObject already exists in the database by:

MainObject.Part = (from s in repoSmallObject.GetAll()

where s.name == MainObject.Part.Name

select s).FirstOrDefault();

Then finally I call the update method in my GenericRepository

repoMainObject.Update(MainObject)

which is defined as a generic repository method:

dbSet.Attach(entity)

context.Entry(entity).State = EntityState.Modified;

context.SaveChanges();

But the relationship doesn't get updated. Why is that? Both objects are attached to context not?

*Edit: The two repo's are injected with the same Context.

And strangely enough the Add method works and also updates the relationship.

网友答案:

When you set
context.Entry(entity).State = EntityState.Modified;
you need at least to set the state after and before updates (i.e. context.Entry(mainObject).CurrentValues and OriginalValues) so EF can build the right UPDATE query (with right WHERE clause). It works if you set
context.Entry(entity).State = EntityState.Added;
because EF needs just to generate an INSERT query.

I don't know exactly why you need it but usually I prefer to attach the object to the DbSet and modify the properties so EF handles various states.

dbSet.Attach(MainObject)
MainObject.Part = (from s in repoSmallObject.GetAll()
            where s.name == MainObject.Part.Name
            select s).FirstOrDefault(); 

(In your case does not work because MainObject.Part.Name does not change)

The attached object should have the same values of the database otherwise you have a concurrency exception.

BTW, why you don't read the old object (MainObject) from the DB than work on it???

相关阅读:
Top