ADO.NET EF 4.1에서 레코드를 어떻게 upsert합니까?

정말 간단한 작업을 수행하려고하는데 Entity Framework 4.1을 사용하여 수행하는 방법을 찾을 수 없습니다.

개체를 수락 한 다음 UPSERT (데이터베이스에 레코드가 있는지 여부에 따라 삽입 또는 업데이트)를 수행하는 컨트롤러 메서드를 원합니다.

자연 키를 사용하고 있으므로 볼 방법이 없습니다. 내 POCO와 그것이 새로운 것인지 아닌지 알려줍니다.

이것이 제가하는 방식이고, 제게는 잘못된 것 같습니다.

[HttpPost]
public JsonResult SaveMyEntity(MyEntity entity)
{            
    MyContainer db = new MyContainer(); // DbContext
    if (ModelState.IsValid)
    {
        var existing =
            db.MyEntitys.Find(entity.MyKey);
        if (existing == null)
        {
            db.MyEntitys.Add(entity);
        }
        else
        {
            existing.A = entity.A;
            existing.B = entity.B;
            db.Entry(existing).State = EntityState.Modified;
        }
        db.SaveChanges();
        return Json(new { Result = "Success" });
    }
}

이상적으로는 모든 것이 다음과 같을 것입니다.

db.MyEntities.AddOrModify(entity);
13
задан Eric Z Beard 28 June 2011 в 18:31
поделиться