【问题标题】:How can I stop EF 7 mapping an entity property to a column?如何停止 EF 7 将实体属性映射到列?
【发布时间】:2015-02-16 21:48:19
【问题描述】:

在 EF 6 中,我可以将 NotMapped 属性添加到属性,然后它不会映射到列。如何在 EF 7 中做到这一点?

【问题讨论】:

    标签: entity-framework-core


    【解决方案1】:

    我们还没有实现数据注释。 (请参阅#107)您应该可以使用 Fluent API 来完成。

    modelBuilder.Entity<MyEntity>().Ignore(e => e.NotMappedProperty);
    

    【讨论】:

    • 知道了。但我注意到Ignore 方法在 EF 7 beta 1 中不可用,没关系。谢谢。
    • @Ricky 如果忽略不可用,你是如何解决的?
    • @fiso 在 beta 8 中,它支持NotMapped 属性,所以只需用[NotMapped] 标记你的实体属性
    • 在 RC1 中,我发现 NotMapped 属性在未映射的只读属性上导致了 StackOverflowException。我不得不求助于使用上面的Ignore() 方法来解决它。
    【解决方案2】:

    只是为了补充 Ricky 和 ​​bricelam 的回答,

    有两种方法可以忽略一个属性:

    1. 模型上的数据注释

      public class Blog
      {
          public int BlogId { get; set; }
          public string Url { get; set; }
      
          [NotMapped]
          public DateTime LoadedFromDatabase { get; set; }
      }
      
    2. Fluent API 覆盖 OnModelCreating

      class MyContext : DbContext
       {
           public DbSet<Blog> Blogs { get; set; }
      
           protected override void OnModelCreating(ModelBuilder modelBuilder)
           {
               modelBuilder.Entity<Blog>()
               .Ignore(b => b.LoadedFromDatabase);
           }
       }
      
       public class Blog
       {
           public int BlogId { get; set; }
           public string Url { get; set; }
      
           public DateTime LoadedFromDatabase { get; set; }
       }
      

    提供文档here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2019-11-01
      • 1970-01-01
      • 2013-04-05
      相关资源
      最近更新 更多