实体框架代码优先:
假设我想创建表关系,哪里是放置代码的好地方?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<table1>().HasMany(i => i.AllowedDestinations).WithMany(d => d.something)
......
或OnModelCreating以外的其他地方?
答案 0 :(得分:1)
您可以创建一个名为“MYEntityConfiguration”的类(其中MyEntity是您尝试配置的实体类型),并从EntityTypeConfiguration&lt;&gt;继承。在实体框架中找到的类型。
例如......
public class Position
{
public int Id { get; set; }
public string CompanyName { get; set; }
public bool IsCurrentRole { get; set; }
public string Summary { get; set; }
public string Title { get; set; }
public int? StartMonth { get; set; }
public int? StartYear { get; set; }
public int? EndMonth { get; set; }
public int? EndYear { get; set; }
public virtual User User { get; set; }
public int UserId { get; set; }
}
和相应的配置文件......
public class PositionConfiguration : EntityTypeConfiguration<Position>
{
public PositionConfiguration()
{
this.ToTable("Positions");
this.HasKey(p => p.Id);
this.Property(p => p.Id).HasColumnName("PositionId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(p => p.CompanyName).HasColumnName("CompanyName");
this.Property(p => p.EndMonth).IsOptional().HasColumnName("EndMonth");
this.Property(p => p.EndYear).IsOptional().HasColumnName("EndYear");
this.Property(p => p.IsCurrentRole).IsOptional().HasColumnName("IsCurrentRole");
this.Property(p => p.StartMonth).IsOptional().HasColumnName("StartMonth");
this.Property(p => p.StartYear).IsOptional().HasColumnName("StartYear");
this.Property(p => p.Summary).HasColumnName("Summary");
this.Property(p => p.Title).HasColumnName("Title");
}
}
然后在你的DBContext中... OnModelCreating ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PositionConfiguration());
base.OnModelCreating(modelBuilder);
}
这将使您的配置保持良好且包含......我发现它是最好的方式。