如何修复“无效的列名'鉴别器'”实体框架错误
本文关键字:鉴别 实体 错误 框架 何修复 无效的列名 无效 | 更新日期: 2023-09-27 18:35:38
我正在使用EF 4.3,并且一直在对我的实体进行一些小的更改,但是没有一个实体类是此错误的一部分。 我想了解为什么这突然开始呕吐。
我的课程:
public class Apple: Fruit
{
public Color Color{ get; set; }
}
public class Fruit: EntityBase
{
public int Size{ get; set; }
public DateTime? DateGrown{ get; set; }
public User GrownBy{ get; set; }
public User SoldBy{ get; set; }
}
public class EntityBase
{
public int Id{ get; set;}
}
现在抛出"无效的列名'鉴别器'"的行:
repository.Apples.Include("GrownBy").Include("SoldBy")
.Where(r => r.GrownBy.Id == user.Id
|| r.SoldBy.Id == user.Id).ToList();
如果我复制该存储库的 SQL。Apple正在尝试运行,并在SSMS中运行它,它运行良好:
SELECT
[Extent1].[Id] AS [Id],
'0X0X' AS [C1],
[Extent1].[DateGrown] AS [DateGrown],
[Extent1].[Color] AS [Color],
[Extent1].[DateGrown] AS [DateGrown],
[Extent1].[GrownBy_Id] AS [GrownBy_Id],
[Extent1].[SoldBy_Id] AS [SoldBy_Id],
[Extent1].[Size] AS [Size],
FROM [dbo].[Fruits] AS [Extent1]
WHERE [Extent1].[Discriminator] = N'Apple'
我尝试添加 [NotMapped] 数据注释作为推荐的@ EF Code First"无效的列名'鉴别器'"但没有继承,例如:
[NotMapped]
public class Apple: Fruit
{
public Color Color{ get; set; }
}
但它会产生一个新错误:
未映射类型"Domain.Entities.Apple"。检查类型 未使用 Ignore 方法显式排除,或者 非映射属性数据注释。验证是否已定义类型 作为一个类,不是原始的、嵌套的或泛型的,并且不继承 来自实体对象。
在以下行:
_context.Database.Initialize(true);
真的开始后悔使用 EF,因为它似乎每周都会弹出这样的新问题。 如果有人能提供有关修复的任何见解,将不胜感激。
编辑:所以看起来它与水果或苹果实体完全无关。 我添加了 User 实体的继承类,这就是导致事情中断的原因。
SQL 数据库映射到代码优先或 C# 代码时存在错误。
如果你认为 SQL 查询通过 SSMS 工作正常,请执行以下步骤。a) 打开"项目解决方案",单击"添加",然后单击"新建项",然后选择"联机",在搜索列中键入 POCO。
b) 安装反向 poco..确保最初将 appconfig 连接字符串名称作为 MyDbContext。c) 生成 poco 类后,您可以看到您的数据库在 C# 代码中映射。
现在,当您的 sql 查询正确时,请尝试使用
[your_dbContext]。Database.ExecuteSqlCommand();或 [your_dbContext]。[表名]。SqlQuery("write your RAW SQL query").ToList();
首先,显示你的 dbContext。现在,尝试手动将列添加到表中,如下所示:
ALTER TABLE MY_TABLE ADD MY_COLUMN NVARCHAR NULL
UPDATE [MY_TABLE] SET [MY_COLUMN]=0 WHERE [MY_COLUMN] IS NULL
ALTER TABLE MY_TABLE ALTER COLUMN MY_COLUMN NVARCHAR NOT NULL
这会在表中添加一个非 NULL 列,因为我很确定实体框架会像这样添加它。另外,如果您将自动迁移启用设置为 true,它应该为您完成此操作(我认为您应该在查询之前尝试),如下所示:
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
如您所见,这是启用迁移时创建的 Configuration.cs 类。 希望这会有所帮助。
如果在实体更改后检查迁移脚本,您将看到正在尝试添加新列(鉴别器)。您收到此错误,因为运行时中没有此列。执行迁移脚本后,错误将消失。