gpt4 book ai didi

c# - 忽略 Entity Framework 4.1 Code First 中的类属性

转载 作者:IT王子 更新时间:2023-10-29 03:28:25 26 4
gpt4 key购买 nike

我的理解是 [NotMapped] 属性直到 EF 5 才可用,目前在 CTP 中,因此我们不能在生产中使用它。

如何将 EF 4.1 中的属性标记为忽略?

更新:我注意到其他一些奇怪的事情。我得到了 [NotMapped] 属性,但出于某种原因,EF 4.1 仍然在数据库中创建一个名为 Disposed 的列,即使 public bool Disposed { get;私有(private)集; } 标记为 [NotMapped]。该类当然实现了 IDisposeable,但我看不出这有什么关系。有什么想法吗?

最佳答案

您可以使用 NotMapped 属性数据注释来指示 Code-First 排除特定属性

public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}

[NotMapped] 属性包含在 System.ComponentModel.DataAnnotations 命名空间中。

您也可以使用 Fluent API 覆盖 DBContext 类中的 OnModelCreating 函数来执行此操作:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

我检查的版本是 EF 4.3,这是您使用 NuGet 时可用的最新稳定版本。


编辑:2017 年 9 月

ASP.NET 核心(2.0)

数据标注

如果您使用的是 asp.net core(撰写本文时为 2.0),则可以在属性级别使用 [NotMapped] 属性。

public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}

流畅的 API

public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}

关于c# - 忽略 Entity Framework 4.1 Code First 中的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com