开发者

What is EntityReference

开发者 https://www.devze.com 2023-03-12 10:21 出处:网络
If I want to bind two Entity Framework objects person1, person2 with parent-son relation. Say, objects are from different ObjectContexts or one is detached. Well and now, I would like to write somethi

If I want to bind two Entity Framework objects person1, person2 with parent-son relation. Say, objects are from different ObjectContexts or one is detached. Well and now, I would like to write something like:

person开发者_StackOverflow中文版1.Parent = person2;

This fails on SaveChanges(). So I write:

person1.ParentReference.EntityKey = person2.EntityKey;

Is this a right solution for that problem or should one always reload the "bad" object (object which is currently in another ObjectContext)?


To give you a direct answer

Image your table

[Tbl_Persons]

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

You will have 2 options to assigning a parent

person1.Tbl_Persons = person2;

where person1 and person2 are both TblPersons objects, or simply assign the Id

person1.ParentId = person2.PersonId;

Now, a complete code as what I normally do to insert/update in the database

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

}

in your Controller:

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

    return RedirectToAction("Index");
}

hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号