0

实体框架代码优先:

假设我要创建表关系,哪里是放代码的好地方?

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<table1>().HasMany(i => i.AllowedDestinations).WithMany(d => d.something)
      ......

还是 OnModelCreating 以外的其他地方?

4

1 回答 1

1

您可以创建一个名为“MYEntityConfiguration”的类(其中 MyEntity 是您尝试配置的实体类型)并从 Entity Framework 中的 EntityTypeConfiguration<> 类型继承。

例如....

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);
        }

这将使您的配置保持良好和包含......我发现它是最好的方式。

于 2012-12-04T13:36:01.943 回答