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
2009-03-08 15:25:50
A:
an old question, but just in case someone needs a code solution:
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
2010-06-28 04:34:03