如果数据库表中不存在列,则排除或忽略实体模型的属性

问题描述

我在实体模型中添加了新属性,因为新列已添加数据库表中。但是在该列中可能会或可能会存在其他客户端数据库中。那么,如何处理呢?我已经尝试过modelBuilder.Entity<Customer>().Ignore(customer => customer.FullName); 但这并不是忽略实体中的属性。因为我们有实体映射的类,所以它不会忽略它。 解决方法好吗?

解决方法

如果添加[NotMapped]属性,则实体框架不会为其创建列。

INSERT INTO table2 (owner_id,month,date,medium,monthly_rent,tax_deduction,final_payment)

SELECT id,'sep2020','2020/10/05',final_payment
 FROM table1

WHERE table1.id =('100','101')

或者如果您想映射该列,但在某些数据库中已经存在,则此迁移将仅在该列不存在时添加该列。

using System.ComponentModel.DataAnnotations.Schema;

namespace DomainModel
{
    public partial class Customer
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [NotMapped]
        public string FullName { get; set; }
    }
}
,

add您需要添加[NotMapped]属性
使用System.ComponentModel.DataAnnotations.Schema;

namespace DomainModel
{
    public partial class Customer
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [NotMapped]
        public string FullName { get; set; }
    }
}

有些人更喜欢Model类,因为它们非常干净-没有任何数据注释。他们更喜欢配置完成DataContext类。 您可以在class属性上使用Ignore方法,以防止其映射到数据库列。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>().Ignore(customer => customer.FullName);
            base.OnModelCreating(modelBuilder);
        }
,

Just stop it。您正在为自己创造一个痛苦的世界。

如果您想拥有动态架构,则根本不应该使用实体框架

通过创建迁移来简化并避免所有这些麻烦,该迁移确保在每个数据库中都创建了该字段(以便在运行时上下文始终与数据库匹配),并确保在应用运行之前执行了迁移。