ef的继承映射真的是能搞死人啊。。。小结一下:
下图中的代码,ResponseTextMessage、ResponseNewsMessage、ResponseMethodMessage等几个类都是ResponseBaseMessage的子类,我要把他们映射到不同的表中,并且用MsgType来区分,并且给他指定固定的值。
这里需要注意的是,每个Map里面都要写 t.ToTable("ResponseBaseMessage");这句,不写就报如标题的这个错。
public class ResponseBaseMessageMap : EntityTypeConfiguration<ResponseBaseMessage> { public ResponseBaseMessageMap() { ToTable("ResponseBaseMessage"); HasKey(x => x.Id); HasMany(x => x.RequestMessages); Map<ResponseTextMessage>(t => { t.ToTable("ResponseBaseMessage"); t.Requires("MsgType").HasValue((int) ResponseMsgType.Text); }); Map<ResponseNewsMessage>(t => { t.ToTable("ResponseBaseMessage"); t.Requires("MsgType").HasValue((int) ResponseMsgType.News); }); Map<ResponseMethodMessage>(t => { t.ToTable("ResponseBaseMessage"); t.Requires("MsgType").HasValue((int) ResponseMsgType.Method); }); Map<ResponseMusicMessage>(t => { t.ToTable("ResponseBaseMessage"); t.Requires("MsgType").HasValue((int)ResponseMsgType.Music); }); } }
子类中其他属性的映射:
public class ResponseNewsMessageMap : EntityTypeConfiguration<ResponseNewsMessage> { public ResponseNewsMessageMap() { this.HasMany(x => x.Items); } }
这篇文章写的还不错:http://www.cnblogs.com/Gyoung/archive/2013/01/25/2874589.html