首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是EntityReference?

什么是EntityReference?
EN

Stack Overflow用户
提问于 2011-06-10 06:32:09
回答 1查看 1.5K关注 0票数 1

如果我想绑定两个实体框架对象person1person2与父子关系.比方说,对象来自不同的ObjectContexts或一个是分离的。好吧,现在,我想写这样的东西:

person1.Parent = person2;

这在SaveChanges()上失败了。所以我写:

person1.ParentReference.EntityKey = person2.EntityKey;

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

EN

回答 1

Stack Overflow用户

发布于 2011-06-10 12:56:44

给你一个直接的回答

想象一下你的桌子

代码语言:javascript
复制
[Tbl_Persons]

PersonId   int [PK]
ParentId   int [FK]
FirstName  nvarchar(100)
LastName   nvarchar(100)
CreateUser int
CreateDate datetime
UpdateUser int
UpdateDate datetime

您将有两个选项来分配一个父级

代码语言:javascript
复制
person1.Tbl_Persons = person2;

其中person1和person2都是TblPersons对象,或者简单地分配Id

代码语言:javascript
复制
person1.ParentId = person2.PersonId;

现在是一个完整的代码,这是我通常对数据库中的插入/更新所做的操作

代码语言:javascript
复制
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

}

在您的控制器中

代码语言:javascript
复制
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Tbl_Persons model, int parentId)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model, parentId, currentUserId);
    }

    return RedirectToAction("Index");
}

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6302755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档