我的数据库中有一个名为SEntries的表(请参见下面的CREATE TABLE语句)。它有一个主键,几个外键,对此没什么特别的。我的数据库中有许多与该表相似的表,但是由于某种原因,该表以EF Proxy Class的“Discriminator”列结尾。

这是在C#中声明类的方式:

public class SEntry
{
    public long SEntryId { get; set; }

    public long OriginatorId { get; set; }
    public DateTime DatePosted { get; set; }
    public string Message { get; set; }
    public byte DataEntrySource { get; set; }
    public string SourceLink { get; set; }
    public int SourceAppId { get; set; }
    public int? LocationId { get; set; }
    public long? ActivityId { get; set; }
    public short OriginatorObjectTypeId { get; set; }
}

public class EMData : DbContext
{
    public DbSet<SEntry> SEntries { get; set; }
            ...
    }

当我尝试向该表添加新行时,出现错误:
System.Data.SqlClient.SqlException: Invalid column name 'Discriminator'.

仅当您从另一个类继承C#类,但是SEntry却不继承任何东西时,才会发生此问题(如上所示)。

除此之外,当我将鼠标悬停在Sentries属性的EMData实例上时,在调试器上获得工具提示时,它会显示:
base {System.Data.Entity.Infrastructure.DbQuery<EM.SEntry>} = {SELECT
[Extent1].[Discriminator] AS [Discriminator],
[Extent1].[SEntryId] AS [SEntryId],
[Extent1].[OriginatorId] AS [OriginatorId],
[Extent1].[DatePosted] AS [DatePosted],
[Extent1].[Message] AS [Message],
[Extent1].[DataEntrySource] AS [DataE...

有什么建议或想法可以帮助您深入了解此问题?我试图重命名表,主键和其他一些东西,但是没有任何效果。

SQL表:
CREATE TABLE [dbo].[SEntries](
[SEntryId] [bigint] IDENTITY(1125899906842624,1) NOT NULL,
[OriginatorId] [bigint] NOT NULL,
[DatePosted] [datetime] NOT NULL,
[Message] [nvarchar](500) NOT NULL,
[DataEntrySource] [tinyint] NOT NULL,
[SourceLink] [nvarchar](100) NULL,
[SourceAppId] [int] NOT NULL,
[LocationId] [int] NULL,
[ActivityId] [bigint] NULL,
[OriginatorObjectTypeId] [smallint] NOT NULL,
CONSTRAINT [PK_SEntries] PRIMARY KEY CLUSTERED
(
[SEntryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[SEntries]  WITH CHECK ADD  CONSTRAINT [FK_SEntries_ObjectTypes] FOREIGN KEY([OriginatorObjectTypeId])
REFERENCES [dbo].[ObjectTypes] ([ObjectTypeId])
GO

ALTER TABLE [dbo].[SEntries] CHECK CONSTRAINT [FK_SEntries_ObjectTypes]
GO

ALTER TABLE [dbo].[SEntries]  WITH CHECK ADD  CONSTRAINT [FK_SEntries_SourceApps] FOREIGN KEY([SourceAppId])
REFERENCES [dbo].[SourceApps] ([SourceAppId])
GO

ALTER TABLE [dbo].[SEntries] CHECK CONSTRAINT [FK_SEntries_SourceApps]
GO

最佳答案

事实证明,Entity Framework将假定从POCO类继承的任何类(映射到数据库上的表)都需要一个Discriminator列,即使派生类不会保存到数据库中也是如此。

解决方案非常简单,您只需要添加[NotMapped]作为派生类的属性即可。

例:

class Person
{
    public string Name { get; set; }
}

[NotMapped]
class PersonViewModel : Person
{
    public bool UpdateProfile { get; set; }
}

现在,即使将Person类映射到数据库上的Person表,也不会创建“Discriminator”列,因为派生类具有[NotMapped]

另外,您可以使用[NotMapped]来设置不想映射到数据库中字段的属性。

关于entity-framework - EF代码优先 “Invalid column name ' Discriminator'”但没有继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6553935/

10-12 03:44