实体框架仅填充域模型中的数据库字段

时间:2012-12-27 18:18:51

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

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

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表中的列。当我运行查询时,实体框架将属性ArchiveIdentifier视为数据库中的列。以下是获取所有DomainModel时生成的SQL的示例。

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

实体框架不会尝试填充Key属性,因为它没有set方法,但它会将ArchiveIdentifier视为表中的列。是否有任何注释或方法告诉实体框架ArchiveIdentifier不是列?

2 个答案:

答案 0 :(得分:4)

使用NotMappedAttribute

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

答案 1 :(得分:0)

在ArchiveIdentifier属性

上使用[NotMapped]数据注释