如何不持久化 EF4 Code First 的属性?

51

有关此事有任何更新吗?我正在使用发布的VS2010和EF4.0,但仍然找不到StoreIgnoreAttribute。它被删除了吗? - Simon Gillbee
5个回答

66

在EF Code-First CTP5中,您可以使用[NotMapped]注释。

using System.ComponentModel.DataAnnotations;
public class Song
{
    public int Id { get; set; }
    public string Title { get; set; }

    [NotMapped]
    public int Track { get; set; }

如果我尝试使用该属性,则会在编译时出现错误。未定义。我们需要什么参考和“using”来解决它? - ProfK
你可能需要添加对 System.ComponentModel.DataAnnotations.dll 的引用,并使用 System.ComponentModel.DataAnnotations; 我已经在我的帖子中更新了一个代码示例。 - Matt Frear
1
当我首先引用System.ComponentModel.DataAnnotations.dll,然后添加对EntityFramework.dll的引用时,我遇到了一个错误。无法解析NotMapped属性。删除并重新添加System.ComponentModel.DataAnnotations.dll引用解决了这个问题。发生在VS2010 SP1中。 - Eric J.
7
我使用了[System.ComponentModel.DataAnnotations.Schema.NotMapped],这似乎解决了问题。 - Clarice Bouwer

4
目前,我知道有两种方法来实现它。
  1. Add the 'dynamic' keyword to the property, which stops the mapper persisting it:

    private Gender gender;
    public dynamic Gender
    {
        get { return gender; }
        set { gender = value; }
    }
    
  2. Override OnModelCreating in DBContext and remap the whole type, omitting the properties you don't want to persist:

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Person>().MapSingleType(p => new { p.FirstName, ... });
    }         
    
使用第二种方法,如果EF团队介绍了Ignore功能,你可以很容易地更改代码为:
     modelBuilder.Entity<Person>().Property(p => p.IgnoreThis).Ignore();

1
我的答案已被@Matt取代。 - Rob Kent

2
如果您不想使用注解,可以使用Fluent API。覆盖OnModelCreating并使用DbModelBuilder的Ignore()方法。假设您有一个“歌曲”实体:
public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Song>().Ignore(p => p.PropToIgnore);
    }
}

您也可以使用EntityTypeConfiguration将配置移动到单独的类中以便更好地管理:
public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new SongConfiguration());
    }

}

public class SongConfiguration : EntityTypeConfiguration<Song>
{
    public SongConfiguration()
    {
        Ignore(p => p.PropToIgnore);
    }
}

1

我不确定这是否已经可用。

在这个 MSDN页面上,介绍了 Ignore 属性和 API,但在评论中,有人在2010年6月4日写道:

您将能够在下一个 Code First 版本中忽略属性


哇,这似乎是代码优先故事中的一个巨大漏洞。如果它们不能包含不直接是数据库行的属性作为数据,那么代码优先实体将很难构建出丰富的领域模型。 - Adam Gordon Bell
1
问题在于Code First还没有RTM版本,目前只是CTP版本,因此它只适用于评估而不适用于生产使用。 - Ladislav Mrnka
同时,创建额外的“属性”作为方法而不是属性,因为这些属性不会被持久化。然后,您可以继续针对适当的对象开发代码。一旦StoreIgnore属性可用,将其更改回属性并更新所有引用就变得很容易了。 - Clicktricity

0

在模型类中添加 System.ComponentModel.DataAnnotations.Schema。(必须包括“SCHEMA”)

在要保留不持久化(即不保存到数据库)的字段上添加 [NotMapped] 数据注释。

这将防止它们作为列添加到数据库表中。

请注意 - 以前的答案可能包含了这些部分,但它们没有完整的“using”子句。它们只是省略了“schema” - 在其中定义了 NotMapped 属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接