我已经在我的实体模型中添加了新属性,因为新列已添加到DB表中。但是在该列中可能在其他客户端数据库中,也可能在其他客户端数据库中。那么,如何处理这个问题呢?我尝试过modelBuilder.Entity<Customer>().Ignore(customer => customer.FullName);,但它并没有忽略entity中的属性。因为我们有实体映射类,所以它不会忽略它。请给我解决方案。
发布于 2020-10-08 21:48:23
如果添加NotMapped属性,实体框架将不会为其创建列。
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; }
}
}或者,如果您想映射列,但在某些数据库中它已经存在,这里有一个迁移,它将仅在列不存在时添加该列。
namespace DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddFullNameToCustomer : DbMigration
{
public override void Up()
{
Sql(@"IF COL_LENGTH('Customer', 'FullName') IS NULL
BEGIN
ALTER TABLE Customer
ADD [FullName] varchar(200) null
END");
}
public override void Down()
{
}
}
}发布于 2020-10-18 10:26:31
addYou需要添加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);
}发布于 2020-10-19 08:15:45
Just stop it。你在为自己创造一个痛苦的世界。
如果你想拥有一个动态的模式,那么你根本就不应该使用实体框架。
通过创建一个迁移,确保在每个数据库中创建字段(以便在运行时,上下文始终与数据库匹配),并确保在应用程序运行之前执行迁移,从而简化并避免所有这些令人头疼的问题。
https://stackoverflow.com/questions/64263473
复制相似问题