实体框架:类型和QUOT;映射为一个复杂类型"错误类型、实体、框架、复杂

2023-09-05 00:40:23 作者:我触及不到的她

在我的数据库,我有一个表称为跟踪与下列:

In my database, I have a table called "tracking" with the following columns:

[OrderNumber] [varchar](50) NULL,
[TrackingNumber] [varchar](50) NULL,
[emailaddress] [varchar](100) NULL,
[courier] [varchar](10) NULL

我有一类叫做跟踪重新present实体从上表:

I have a class called Tracking to represent entities from the table:

public class Tracking
{
    public virtual string OrderNumber { get; set; }
    public virtual string TrackingNumber { get; set; }
    public virtual string EmailAddress { get; set; }
    public virtual string Courier { get; set; }
}

在我的数据上下文的定义

In the definition of my data context

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new TrackingConfig());
}

internal class TrackingConfig : EntityTypeConfiguration<Tracking>
{
    internal TrackingConfig()
    {
        Property(x => x.OrderNumber);
        Property(x => x.TrackingNumber);
        Property(a => a.EmailAddress).HasColumnName("emailaddress");
        Property(a => a.Courier).HasColumnName("courier");
    }
}

正如你所看到的,我没有明确投它作为一个复杂类型。我甚至用HasColumnName指定哪些列名映射到类的哪个属性,以防万一它没有认识到它们由于资本的差异。 (我收到的错误发生,无论与否HasColumnName时,事实证明。)

As you can see I'm not explicitly casting it as a complex type. I even used HasColumnName to specify which column name maps to which property of the class, just in case its failing to recognize them due to the differences in capitalization. (The error I'm getting happens regardless of whether or not HasColumnName is used, as it turns out.)

当我引用我已经建立了以任何理由存储库,初始化失败和实体框架抛出一个异常:

When I invoke the repository I've set up for any reason, the initialization fails and Entity Framework throws an exception:

The type 'Tracking' is mapped as a complex type. The Set method, DbSet objects, and DbEntityEntry objects can only be used with entity types, not complex types.

我不设置它作为一个复杂类型...为什么EF4对待它就像一个?

I'm not setting it as a complex type... why is EF4 treating it like one?

推荐答案

看起来它必须与申报领域为虚。您还可以使用数据标注覆盖表和列名,以配合您现有的数据库架构。下面是我会成立了POCO模型和的DbContext。

Looks like it has to do with declaring fields as virtual. You can also use data annotations to override table and column names to match your existing db schema. Below is how I would set up the POCO model and dbcontext.

[Table("tracking")]
public class Tracking
{
    public string OrderNumber { get; set; }
    public string TrackingNumber { get; set; }

    [Column(Name = "emailaddress")]
    public string EmailAddress { get; set; }

    [Column(Name = "courier")]
    public string Courier { get; set; }
}

public class TrackingEntities : DbContext
{
    public DbSet<Tracking> Trackings { get; set; }
}