将 [NotMapped] 添加到部分 class 是否避免映射整个 class?
Does adding [NotMapped] to a partial class avoid mapping the entire class?
我已经设置了我的 EF 代码优先数据库,但想要添加其他派生属性。 (是的,它应该在视图模型中,我们可以下次再讨论为什么会这样。)我创建了一个部分 class 扩展了实际的 table class。如果我将 [NotMapped]
添加到新的部分,它会避免映射我在那里添加的其他属性,还是会应用于整个 class?
它将应用于整个 class。请记住,部分 class 只是将 class 拆分为多个文件的一种方式。来自 official docs:
At compile time, attributes of partial-type definitions are merged.
所以这个:
[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; }
}
如果要添加部分 class 而模型中不包含属性,则需要将 NotMapped
属性添加到各个项目:
partial class PartialEntity
{
public string Title { get; set; }
}
partial class PartialEntity
{
[NotMapped]
public string Name { get; set; }
}
我已经设置了我的 EF 代码优先数据库,但想要添加其他派生属性。 (是的,它应该在视图模型中,我们可以下次再讨论为什么会这样。)我创建了一个部分 class 扩展了实际的 table class。如果我将 [NotMapped]
添加到新的部分,它会避免映射我在那里添加的其他属性,还是会应用于整个 class?
它将应用于整个 class。请记住,部分 class 只是将 class 拆分为多个文件的一种方式。来自 official docs:
At compile time, attributes of partial-type definitions are merged.
所以这个:
[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; }
}
如果要添加部分 class 而模型中不包含属性,则需要将 NotMapped
属性添加到各个项目:
partial class PartialEntity
{
public string Title { get; set; }
}
partial class PartialEntity
{
[NotMapped]
public string Name { get; set; }
}