【问题标题】:Entity Framework - Add reference to abstract navigation property without loading实体框架 - 添加对抽象导航属性的引用而不加载
【发布时间】:2016-07-21 12:42:10
【问题描述】:

添加对非抽象导航属性的引用很好:

class Entity {
    int Id { get; set; }

    Reference Reference { get; set; }
    Parent Other { get; set; }
}

class Reference {
    int Id { get; set; }
}

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

class Child : Parent { }

async Task DbMethod() {
    using(var context = new XYZDbContext()) {
        var reference = new Reference { Id = 6 };
        context.Attach(reference);

        var entity = new Entity {
            Id = 3,
            Reference = reference,
        };

        context.Add(entity);

        await context.SaveChangesAsync();
    }
}

但是,如果我想将 Other 属性设置为现有记录(例如 id 42),我不能像使用 Reference 类一样实例化 Parent 类(因为它是抽象的)。

如何为抽象 Parent 类添加对现有实体的引用?我想我可以将OtherId 属性添加到Entity 类并设置它,但我想尽可能避免污染实体

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    为什么不把你的抽象类改成非抽象类

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

    所以你现在可以实例化它并且行为是相同的。 根据您的示例,您的抽象类没有表现得像抽象类。

    【讨论】:

    • 这个例子是为了简洁起见而设计的。该类需要是抽象的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多