我正在尝试基于http://www.schema.org上定义的实体使用 Code First 和迁移来构建实体模型和数据库。底线是所有实体都继承自实体“事物”。
迁移会构建数据库,但任何对数据库进行种子设定的尝试都会失败。
一切都继承自 Thing:
namespace Entities.Models
{
public class Thing
{
public Thing()
{
Id = Guid.NewGuid();
Name = String.Empty;
}
public Guid Id { get; set; }
public virtual string Name { get; set; }
}
public class Person : Thing
{
public Person()
: base()
{
Friends = new List<Person>();
}
public string GivenName { get; set; }
public string FamilyName { get; set; }
public string Email { get; set; }
public virtual ICollection<Person> Friends { get; set; }
}
public class Event : Thing
{
public Event()
: base()
{
Attendees = new List<Person>();
}
public virtual ICollection<Person> Attendees { get; set; }
public TimeSpan Duration { get; set; }
public DateTime? endDate { get; set; }
public DateTime? StartDate { get; set; }
}
public class ThingMap : EntityTypeConfiguration<Thing>
{
public ThingMap()
{
// Primary Key
this.Property(t => t.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Properties
this.Property(t => t.Name)
.IsOptional()
.HasMaxLength(200);
// Table & Column Mappings
this.ToTable("entity_Thing");
}
}
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Properties
this.Map<Person>(t =>
{
t.MapInheritedProperties();
t.ToTable("entity_Person");
});
// Table & Column Mappings
}
}
public class EventMap : EntityTypeConfiguration<Event>
{
public EventMap()
{
// Properties
this.Map<Event>(t =>
{
t.MapInheritedProperties();
t.ToTable("entity_Event");
});
// Table & Column Mappings
}
}
public class CitriusSpotsContext : DbContext
{
static CitriusSpotsContext()
{
Database.SetInitializer<CitriusSpotsContext>(null);
}
public CitriusSpotsContext()
: base("Name=CitriusSpotsContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ThingMap());
modelBuilder.Configurations.Add(new PersonMap());
modelBuilder.Configurations.Add(new EventMap());
}
public DbSet<Thing> Things { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Event> Events { get; set; }
}
}