更新使用MVC 4和Entity Framework相关的数据? [英] Updating related data using MVC 4 and Entity Framework?
问题描述
所以,我在保存其中包含相关的实体,当我保存它的新关系的空白创建数据的问题。
So, I have a problem in save data which contains related entities, when I save it a new relation blank is created.
例:
实体:
public class Project
{
public int Id { get; set; }
public int Code{ get; set; }
public string Description{ get; set; }
public virtual Client Client { get; set; }
}
public class Client
{
public int Id { get; set; }
public int Code { get; set; }
public string Name { get; set; }
}
控制器GET:
public ActionResult Create()
{
PopulateDropDownClienteList(String.Empty); //Returns to ViewBag to create a combobox .in view
return View();
}
视图:
@Html.DropDownListFor(m => m.Client.Id, new SelectList(ViewBag.Client_Id, "Id", "Name"), new { Name = "Client.Id" });
控制器POST:
The Controller POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string command, Project project)
{
try
{
if (ModelState.IsValid)
{
projectRepository = new ProjeRepository();
Project pro = projectRepository.ReturnByCode(project.Code);
if (pro == null)
projectRepository.Save(project);
else
projectRepository.Update(project);
PopulateDropDownClienteList(String.Empty);
Return View();
}
else
{
return View(project);
}
}
catch (Exception ex)
{
return View();
}
}
所以,当我保存数据,客户端不与项目关联。只是创造一个新的空白客户端。
So when I save the data, the client is not associated with the project. just creating a new blank Client.
推荐答案
您项目保存code未更新的实体,它的添加新所有的时间。
You Project Save code is not updating the entity, it is ADDING a new one all the time.
您应该有类似以下理由更新逻辑 -
You should have update logic similar to following grounds -
添加新条目FK,并将它与父记录关联 -
var entity = entities.Students.Where(p => p.Id == "2").First();
entity.StudentContact = new StudentContact() { Contact = "xyz", Id = "2" };
entities.Students.Attach(entity);
var entry = entities.Entry(entity);
// other changed properties
entities.SaveChanges();
要使用新的细节更新FK纪录 -
var entity = entities.Students.FirstOrDefault();
entity.StudentContact.Contact = "ABC";
entities.Students.Attach(entity);
var entry = entities.Entry(entity);
entry.Property(e => e.StudentContact.Contact).IsModified = true;
// other changed properties
entities.SaveChanges();
以上code,我有与StudentContacts FK关系的学生档案。我更新一个学生的联系信息,然后利用其附加更新到数据库中。
The above code, I have a Student records which has FK relationship with StudentContacts. I updated Contact information of a student and then updated it to database using ATTACH.
这篇关于更新使用MVC 4和Entity Framework相关的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!