在不更改子实体的情况下更新父实体

Updating parent entity without changing the children

我有一个一对多的关系...我在网络环境(断开连接的环境)中工作。想象一下,用户只想更新父实体,而不必加载所有子实体,这可能吗?

这是代码:

public class Parent
{
    public int Id { get; set; }

    public string Description { get; set; }

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

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }

    public Parent Parent { get; set; }

    public string Data { get; set; }
}

我想用 id = 5 更新 Parent 的描述,新描述来自用户:

Parent parent = new Parent()
{
    Id = 5, // I already know the user Id
    Description = "new description from User";
    Children = null; // I don't want the children to be changed
}

dbContext.Parent.Attach(parent);
dbContext.Entry(parent).State = EntityState.Modified;
dbContext.SaveChanges();

我不确定这是否正确?现有 Children 是否会被删除(因为子列表为空)?

is it possible?

是的,你做得对。

根据你的样本

dbContext.Parent.Attach(parent);
dbContext.Entry(parent).State = EntityState.Modified;
dbContext.SaveChanges();

仅对 parent table 有效。