Question

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?

Was it helpful?

Solution

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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top