Question

I am using EF 5 Beta 2 Code-First. I have created an edmx file which has 2 entities among others named Brand and Vehicle.

One Brand can have zero or more (many) Vehicles and every Vehicle should have a Brand (required). Vehicle has a foreign key named BrandID which is non-nullable.

(relationship)   
    Brand  +------------------->  Vehicle
          (1)                  (*)

Also I did use EF 5 DbContext Generator to create POCO classes.

The Problem

When I try to either Read or Write records, I get the following error:

error 3023: Problem in mapping fragments starting at line 155:Column Vehicle.BrandID in table Vehicle must be mapped: It has no default value and is not nullable.

Notice: I am using TPC inheritance mapping where Vehicle is an abstract base class from which 2 classes (Car & Motorbike) are being derived.

Here is class definition plus related fluent API code:

//------------ Class definiions ---------------

public abstract partial class Vehicle
{
    public int VehicleID { get; set; }
    public short BrandID { get; set; }

    public virtual Brand Brand { get; set;
}

public partial class Car : Vehicle
{
    public string BodyType { get; set; }
}

public partial class Motorbike : Vehicle
{
}

public partial class Brand
{
    public Brand()
    {
        this.Vehicles = new HashSet<Vehicle>();
    }        

    public short BrandID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Vehicle> Vehicles { get; set; }
}


//--------------- Fluent API code ---------------

modelBuilder.Entity<Vehicle>()
    .Property(p => p.VehicleID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);    

modelBuilder.Entity<Car>()
    .Map(m =>
    {
        m.ToTable("Car");
        m.MapInheritedProperties();
    });

modelBuilder.Entity<Motorbike>()
    .Map(m =>
    {
        m.ToTable("Motorbike");
        m.MapInheritedProperties();
    });

modelBuilder.Entity<Brand>()
    .HasMany(b=>b.Vehicles)
    .WithRequired(v=>v.Brand)
    .HasForeignKey(p => p.BrandID);


modelBuilder.Entity<Brand>()
    .Property(p => p.BrandID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

This is so strange since everything seems OK and has been checked several times.

Any thoughts would be greatly appreciated.

Was it helpful?

Solution

TPC inheritance just doesn't work for this kind of model where you have a navigation property on the base type:

...using TPC in the EF forces you to avoid associations in your base type...

(Quote from here: http://blogs.msdn.com/b/alexj/archive/2009/04/15/tip-12-choosing-an-inheritance-strategy.aspx)

You must use TPT or TPH inheritance for your model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top