views:

2472

answers:

5

Hi, I transfer data between the entity framework and the business layer and user layer by using Data Transfer Objects. I do have some doubt, if I retrieve an object which is converted to a DTO, how do I update the correct object in the entity framework and not just insert a douplicate?

A: 

You would need to include a primary or alternate key in the DTO, then match that key back to the correct EF entity upon update.

John Saunders
A: 

So if I just remember to set the correct primary key on the object, the Entity Framework knows if it should update or save a new instance of the object?

A: 

No one who can help?

A: 

Changoleon.

A: 

an old question, but just in case someone needs a code solution:

http://www.mikesdotnetting.com/Article/110/ASP.NET-MVC-Entity-Framework-Modifying-One-to-Many-and-Many-to-Many-Relationships

Example:

public void EditArticle(Article article, string articleTypeId, string[] categoryId)

{

var id = 0;

Article art = de.ArticleSet

              .Include("ArticleTypes")

              .Include("Categories")

              .Where(a => a.ArticleID == article.ArticleID)

              .First();

var count = art.Categories.Count;

for (var i = 0; i < count; i++)

{

art.Categories.Remove(art.Categories.ElementAt(i));

count--;

}

foreach (var c in categoryId)

{

id = int.Parse(c);

Category category = de.CategorySet.Where(ct => ct.CategoryID == id).First();

art.Categories.Add(category);

}

art.Headline = article.Headline;

art.Abstract = article.Abstract;

art.Maintext = article.Maintext;

art.DateAmended = DateTime.Now;

art.ArticleTypesReference.EntityKey = new EntityKey(

                                         "DotnettingEntities.ArticleTypeSet", 

                                         "ArticleTypeID", 

                                         int.Parse(articleTypeId)

                                         );

de.SaveChanges();

}

user1111111