문제

So I am sending an object to a method. In the method, if the object already exists in the database, I want the existing row updated. If the object does not exist in the database, I want a new row added.

I have wasted a few hours trying to make this work, but none of the solutions I have found seem to work. Either intellisense does not like the code or some other problem comes up.

The solution is ASP.NET Webforms using .NET 4.0, so I am assuming that I have Entity Framework v4.0.

Below is the current code. I have no intellisense entry for .Entry so to resolve this, I have tried using .ObjectStateManager.ChangeObjectState instead but that does not seem to have the same functionality.

var itemInDb = _dbSet.SingleOrDefault(c => c.Id == company.Id);
if (itemInDb != null)
{
    _context.Entry(itemInDb).CurrentValues.SetValues(company);
}
else
{
    _dbSet.Add(company);
}
_context.SaveChanges();
도움이 되었습니까?

해결책 3

This worked:

if (context.tblVehicleMaint.Any(e => e.ActivityID == mo.AID && e.VID == mo.VID))
                {
                    context.tblVehicleMaint.Attach(mo);
                    context.ObjectStateManager.ChangeObjectState(mo, System.Data.EntityState.Modified);
                }
                else
                {
                    context.tblVehicleMaint.AddObject(mo);
                }

                context.SaveChanges();

다른 팁

DbPropertyValues.SetValues Method:

[This page is specific to the Entity Framework version 6.0 Beta. The latest version is available as the 'Entity Framework' NuGet package. For more information, see Entity Framework Releases and Versioning.]

You say you have Entity Framework v4.0.


And EF 5 seems Ok too

The easy thing to do is delete the old one and then add the or attach the new one. This way entity framework should set the entity State to modified for that id

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top