【问题标题】:Does adding [NotMapped] to a partial class avoid mapping the entire class?将 [NotMapped] 添加到部分类是否会避免映射整个类?
【发布时间】:2016-08-25 13:32:58
【问题描述】:

我已设置我的 EF 代码优先数据库,但想添加其他派生属性。 (是的,它应该在视图模型中,我们可以下次讨论为什么会这样。)我创建了一个扩展实际表类的局部类。如果我将[NotMapped] 添加到新的部分,它会避免映射我在那里添加的其他属性还是会应用于整个类?

【问题讨论】:

    标签: c# entity-framework ef-code-first code-first


    【解决方案1】:

    它将适用于整个班级。请记住,部分类只是将类拆分为多个文件的一种方式。来自official docs

    在编译时,部分类型定义的属性被合并。

    所以这个:

    [SomeAttribute]
    partial class PartialEntity
    {
        public string Title { get; set; }
    }
    
    [AnotherAttribute]
    partial class PartialEntity 
    {
        public string Name { get; set; }
    }
    

    相当于写:

    [SomeAttribute]
    [AnotherAttribute]
    partial class PartialEntity
    {
        public string Title { get; set; }
        public string Name { get; set; }
    }
    

    如果您想在模型中不包含属性的情况下添加部分类,则需要将NotMapped 属性添加到各个项目:

    partial class PartialEntity
    {
        public string Title { get; set; }
    }
    
    partial class PartialEntity 
    {
        [NotMapped]
        public string Name { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多