[英]How To Save Navigation Properties in the Entity Framework
I'm trying to use the repository pattern to save an entity using the Entity Framework. 我正在尝试使用存储库模式来使用实体框架保存实体。 I'm unclear on how to save the Navigation Properties (like Account below). 我不清楚如何保存导航属性(如下面的帐户)。 Can anyone shed some light on this. 任何人都可以对此有所了解。 Especially how one would set the AccountId from an MVC controller all the way through to the repository where it's saved. 特别是如何将AccountId从MVC控制器一直设置到保存它的存储库。
Thanks! 谢谢!
--- Sample Code --- ---样本代码---
public void SavePerson(Person person)
{
if (person != null)
{
using (xxxxxxEntities bbEntities = new xxxxxxEntities())
{
//see if it's in the db
Person cPerson;
ObjectQuery<Person> persons = bbEntities.Person;
cPerson = (from p in persons
where p.PersonId == person.PersonId
select p).FirstOrDefault() ?? new Person();
//synch it
cPerson.Account.AccountId = person.Account.AccountId; //<=== ????
cPerson.Active = person.Active;
cPerson.BirthDay = person.BirthDay;
cPerson.BirthMonth = person.BirthMonth;
cPerson.BirthYear = person.BirthYear;
cPerson.CellPhone = person.CellPhone;
cPerson.CreatedBy = person.CreatedBy;
cPerson.CScore = person.CScore;
Etc....
I think you may be going about this the hard way. 我想你可能会以艰难的方式解决这个问题。 There are lots of posts on the repository pattern, the way that works best with MVC is to get the item, then update it with the form, then save it. 存储库模式上有很多帖子,最适合MVC的方法是获取项目,然后使用表单更新它,然后保存它。 What you're doing is passing the item through to your repository, getting it again and then updating it with the object. 您正在做的是将项目传递到您的存储库,再次获取它,然后使用该对象更新它。
But that's not the problem you asked about; 但那不是你问过的问题;
cPerson.Account = (from a in Account
where a.AccountId.Equals(person.Account.AccountId)
select a).FirstOrDefault();
You need to set the Account object to an instance of the account you're trying to reference like this. 您需要将Account对象设置为您尝试引用的帐户的实例,如下所示。 You could, and probably should, extract this code into a seperate repository for the account, just make sure they share the same Entity context. 您可以并且可能应该将此代码提取到该帐户的单独存储库中,只需确保它们共享相同的实体上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.