【问题标题】:Entity Framework populate only the database fields in domain model实体框架仅填充域模型中的数据库字段
【发布时间】:2025-12-10 21:40:01
【问题描述】:

我有一个域模型,它具有数据库中不存在的属性。比如……

public class DomainModel: IKeyedEntity
{
    //Id for the table
    public int DomainModelID { get; set; }

    //Foreign key value
    public int FooID { get; set; }

    //Text value
    public string Value { get; set; }

    //Generic reference to the id of the table
    public int Key { get { return this.DomainModelID; } }

    //No a column in the database
    public Guid ArchiveIdentifier
    {
        get { return Foo.ArchiveIdentifier; }
        set { Foo.ArchiveIdentifier = value }
    }

    //Navigation Property
    public virtual Foo Foo { get; set; }
}

如您所见,属性 KeyArchiveIdentifier 不是 DomainModels 表中的列。当我运行查询时,Entity Framework 将属性 ArchiveIdentifier 视为数据库中的一列。以下是获取所有 DomainModels 时生成的 SQL 示例。

SELECT 
[Extent1].[DomainModelID] AS [DomainModelID], 
[Extent1].[FooID] AS [FooID], 
[Extent1].[Value] AS [Value],
[Extent1].[ArchiveIdentifier] AS [ArchiveIdentifier] 
FROM  [dbo].[DomainModels] AS [Extent1]

Entity Framework 不会尝试填充Key 属性,因为它没有设置方法,但是它将ArchiveIdentifier 视为表中的一列。是否有任何注释或方法告诉 Entity Framework ArchiveIdentifier 不是列?

【问题讨论】:

    标签: c# sql entity-framework domain-model


    【解决方案1】:

    使用NotMappedAttribute

    [NotMapped]
    public Guid ArchiveIdentifier
    {
        get { return Foo.ArchiveIdentifier; }
        set { Foo.ArchiveIdentifier = value; }
    }
    

    【讨论】:

      【解决方案2】:

      在 ArchiveIdentifier 属性上使用 [NotMapped] 数据注释

      【讨论】: