Reputation: 2028
I'm attempting a little EF with code first - and I can't figure out where I have gone wrong with the is simply example of my own. I'm just out of ideas, and would like to nail down where I'm going wrong...
First the simply POCO class representing a location - a location can be a RadioStation, or a Merchant. I haven't added additional fields (which will come later), so right now it's just a TPH in as simple config as I can make it.
namespace EFDataClasses.Entities
{
public class RadioStation : Location
{
public RadioStation()
{
}
}
public class Merchant : Location
{
public Merchant()
{
}
}
public class Location
{
public Location()
{
}
public int Loc_ID { get; set; }
public string Loc_Code { get; set; }
public string Loc_Name { get; set; }
public string Loc_Type {get;set;}
}
}
then the config class:
namespace EFDataClasses.Mapping
{
public class LocationMap : EntityTypeConfiguration<Location>
{
public LocationMap()
{
// Primary Key
this.HasKey(t => t.Loc_ID);
// Properties
this.Property(t => t.Loc_ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Properties
this.Property(t => t.Loc_Code)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.Loc_Name)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.Loc_ID).HasColumnName("Loc_ID");
this.Property(t => t.Loc_Code).HasColumnName("Loc_Code");
this.Property(t => t.Loc_Name).HasColumnName("Loc_Name");
//my discriminator property
this.Property(t => t.Loc_Type).HasColumnName("Loc_Type").HasColumnType("varchar").HasMaxLength(50).IsRequired();
// Table & Column Mappings
this.Map(m =>
{
m.ToTable("Location");
m.Requires("Loc_Type").HasValue("Location");
}
)
.Map<RadioStation>(m =>
{
m.ToTable("Location");
m.Requires("Loc_Type").HasValue("RadioStation");
}
)
.Map<Merchant>(m =>
{
m.ToTable("Location");
m.Requires("Loc_Type").HasValue("Merchant");
}
)
;
}
}
}
here is the context:
namespace EFDataClasses
{
public class MyContext : DbContext
{
static MyContext()
{
Database.SetInitializer<MyContext>(new DropCreateDatabaseAlways<MyContext>());
}
public DbSet<EFDataClasses.Entities.Location> Locations {get; set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new LocationMap());
}
}
}
and finally the program class which attempts to add radio station..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EFConsole
{
class Program
{
static void Main(string[] args)
{
var db = new EFDataClasses.MyContext();
db.Locations.Add(new EFDataClasses.Entities.RadioStation() { Loc_Name = "Radio Station Name 1", Loc_Code = "RD1" });
int chngs = db.SaveChanges();
System.Diagnostics.Debugger.Break();
}
}
}
The error that I'm getting is a validation error on Loc_Type saying that it's a required field. My impression here is that EF would fill that in when I select the appropriate type - and all my reading supports that.
If I do add the appropriate location type - EF give me another error....
arggghhh!
In the end I would like to make Location abstract but does that mean I can drop the hasvalue("Location")?
I would like to move on here, but I'm curious where I have done wrong. thanks!
Upvotes: 1
Views: 1712
Reputation: 14302
I think you're over-complicating things a bit, and that's dangerous around CF.
With code-first, you have to stick to 'tried and tested' patterns that work, otherwise mixing things and constructs will get you into trouble soon enough.
First, why do you need to map and have Loc_Type at all, I mean in the class model? That's superfluous, you'll get that with your 'class' type really, your class type is the discriminator and vice versa.
And that's what the error is saying pretty much I think, either supply or 'drop the column from mapping' or something.
So just drop that from the 'Location'
and it works w/o problems. Also you don't really need to specify discriminator most of the time unless you want to have your Db makes sense and used by other sides etc. which is ok though.
If you want you can make it abstract, Location - and that's normally done, and I think you can drop it then from the mappings, only 'real implemented' classes should be mapped as only those could be 'instantiated'.
And lastly, TPH is for various reasons not the most 'fortunate' solution, and the most error prone of all I think, TPT, TPC all work much more 'fluid'. You cannot have your 'child classes' 'properties be non null, etc. etc. there are posts on that.
hope this helps.
EDIT: if you'd like to control the 'hidden' discriminator I think
you could try and manually adjust the migration file
for that column specifically, to set it's size etc. If that is important (code first should pick the right values there I guess). If you don't change anything significant to the sense of how things work that should work.
Upvotes: 1
Reputation: 7523
The problem is that when you use a column as a discriminator for TPH mapping you cannot also map that column to a property in your class. This is because EF is now controlling the value of that column based on the type of .NET class. So you should remove this line that does the mapping of the Loc_Type property to the Location column:
// Remove this line:
this.Property(t => t.Loc_Type).HasColumnName("Loc_Type").HasColumnType("varchar").HasMaxLength(50).IsRequired();
If you need (or want) to specify an explicit column type, size, etc for the discriminator column then you can do that in the Map call. For example:
Map(m =>
{
m.ToTable("Location");
m.Requires("Loc_Type")
.HasValue("Location")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
}
You don't need to have any property in the class representing the location type. If you do want to get a string value equivalent of Loc_Type then you can use something like this in Location:
public virtual string Loc_Type
{
get { return "Location"; }
}
Then override it in the other classes. For example:
public override string Loc_Type
{
get { return "RadioStation"; }
}
The rest of the code looks fine.
Upvotes: 1