Entity Framework: Type “mapped as a complex type” Error

时间秒杀一切 提交于 2020-01-04 01:12:54

问题


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

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");
    }
}

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.

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


回答1:


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; }
}


来源:https://stackoverflow.com/questions/14404813/entity-framework-type-mapped-as-a-complex-type-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!