繁体   English   中英

EF4.1使用ICollection属性的子项更新数据

[英]EF4.1 Updating data with child that is ICollection property

我正在尝试使用Entity Framework和ICollection子属性更新数据库数据。

对于INSERT情况,EF会自动保存子数据,但对于Updating情况则不会。

所以我做了手动更新,但是我想有一种我不知道的自动更新方法。

请查看我的代码,并给我建议

public class Parent
{
    [Key]
    public int ID {get; set;}   
    public string Name {get; set;}

    public virtual ICollection<Child> Children{ get; set; }
}

public class Child
{
    [Key]
    public int ID {get; set;}
    public int ParentID { get; set; }
    public string Name {get; set;}
}

// INSERT的控制器方法

public void InsertTest(){
    //generate new Parent Data with child
    Parent parent = new Parent() { 
        Name = "Nancy"
    };

    parent.Children.Add(new Child()
    {
        Name = "First Son"
    });

    parent.Children.Add(new Child()
    {
        Name = "Second Son"
    });

    var parentRepository = unitofwork.parentRepository;
    parentRepository.insert(parent); //context.Set<Parent>().Add(parent);
    unitofwork.Save();
    // it save child entity well
}

// UPDATE的控制器方法

public void UpateTest()
{
    //generate new Parent Data with child
    Parent parent = new Parent()
    {
        ID = 1,
        Name = "Nancy"
    };

    parent.Children.Add(new Child()
    {
        ID = 1,
        ParentID = 1,
        Name = "First Son Renamed"
    });

    parent.Children.Add(new Child()
    {
        ID = 2,
        ParentID = 1,
        Name = "Second Son"
    });

    // add new data
    parent.Children.Add(new Child()
    {
        Name = "Third Son"
    });

    var parentRepository = unitofwork.parentRepository;
    parentRepository.update(parent); //context.Set<Parent>().Attach(entityToUpdate); context.Entry(entityToUpdate).State = EntityState.Modified;
    unitofwork.Save();
    // it save parent data, but it does not change any for child data

    // *** To make work, I did like this, ***
    // var childRepository = unitofwork.childRepository;
    //foreach (Child c in parent.Children.ToList())
    //{
    //    if (c.ID < 1)
    //    {
    //        childRepository.update(c);
    //    }
    //    else
    //    {
    //        childRepository.insert(c);
    //    }
    //}

    //unitofwork.Save();

    // then it works.
}

由于您没有直接附加所选内容并将其标记为脏内容,因此EF无法在不丢失其原始值的情况下检测到它们已更改。

从数据库中加载子项并将值注入它们(特别是在您还希望删除列表中不再选择的子项时很有用),或者使用工作单元在附加子项后将其标记为已修改(但是,dB操作较少),不会删除现有的孩子)。

从您的代码中,我假设update()方法是将实体标记为肮脏的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM