C# 什么是实体引用

C# 什么是实体引用,c#,.net,entity-framework,C#,.net,Entity Framework,如果我想用父子关系绑定两个实体框架对象person1和person2。比如说,对象来自不同的ObjectContext,或者一个是分离的。好吧,现在,我想写一些东西,比如: person1.Parent=person2 这在保存更改时失败。所以我写: person1.ParentReference.EntityKey=person2.EntityKey 这是该问题的正确解决方案,还是应该始终重新加载当前位于另一个ObjectContext中的坏对象?为您提供直接答案 想象你的桌子 [Tbl_Pe

如果我想用父子关系绑定两个实体框架对象person1和person2。比如说,对象来自不同的ObjectContext,或者一个是分离的。好吧,现在,我想写一些东西,比如:

person1.Parent=person2

这在保存更改时失败。所以我写:

person1.ParentReference.EntityKey=person2.EntityKey


这是该问题的正确解决方案,还是应该始终重新加载当前位于另一个ObjectContext中的坏对象?

为您提供直接答案

想象你的桌子

[Tbl_Persons]

PersonId   int [PK]
ParentId   int [FK]
FirstName  nvarchar(100)
LastName   nvarchar(100)
CreateUser int
CreateDate datetime
UpdateUser int
UpdateDate datetime
您将有两个选项来指定父级

person1.Tbl_Persons = person2;
其中person1和person2都是TblPersons对象,或者只是分配Id

person1.ParentId = person2.PersonId;
现在,一个完整的代码,就像我通常在数据库中插入/更新的代码一样

在控制器中:


希望有帮助。

我不认为您应该直接设置引用,它可能会绕过一些跟踪内容。请提供如何在保存更改时失败的详细信息?
public class MyRepository : IMyRepository
{
    MyEntities db = new MyEntities();
    DateTime now = DateTime.UTCNow;

    public void Save() {
        db.SaveChanges();
    }

    #region Update / Insert Persons

    public void UpdatePerson(Tbl_Persons person, int parentId, int userId)
    {
        // let's check if record is in db
        Tbl_Persons p = this.GetPersonById(person.PersonId); 
        if(p == null)
            p = new Person(); // person was not found in db

        p.FirstName = person.FirstName;
        p.LastName = person.LastName;

        // we can now hook up the parent object in 2 ways
        // or set the Id, or attach the hole object
        // NOTE: only choose one line!
        p.MyParent = parentId;
        p.TblParent = this.GetPersonById(parentId);

        // update info
        p.UpdateDate = now;
        p.UpdateUser = userId;


        if(p.PersonId == 0)
        {
            // is it new person in db, so we need to INSERT into the db
            p.CreateDate = now;
            p.CreateUser = userId;

            db.Tbl_Persons.AddObject(p);
        }
        else
        {
            // It's an existing person, we do need need to do anything
            // as internally once we assign a new value to the object that
            // come back from the database, EF sets Modified flag on this
        }

        // let's save
        this.Save();
    }

    #endregion

    #region Queries

        public Tbl_Persons GetPersonById(int personId)
        { 
            return db.Tbl_Persons.FirstOrDefault(x => x.PersonId == personId);
        }

    #endregion

}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Tbl_Persons model, int parentId)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model, parentId, currentUserId);
    }

    return RedirectToAction("Index");
}