我有两个表需要连接。在每个表中,分别插入数据。问题是,在将数据插入两个表之后,OnModelCreating方法中新创建的表仍然是空的吗?!
抱歉我的英文。
我在这里附上代码以便更好地理解:
Advertisement.cs
public class Advertisement {
[Key]
public int AdvertisementID { get; set; }
[Required]
public DateTime CreateDate { get; set; }
[Required MaxLength(256)]
public string Title { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int? TypeOfAd { get; set; }
[Required]
public bool IsTop { get; set; }
[Required]
public int Price { get; set; }
public int Views { get; set; }
[Required]
public bool IsActive { get; set; }
public int? SubcategoryID { get; set; }
public virtual Subcategory Subcategory { get; set; }
[Required]
public string UserName { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Photo> Photos { get; set; }
}
Photo.cs
public class Photo {
[Key]
public int PhotoID { get; set; }
[Required(MaxLength(512)]
public string ImageUrl { get; set; }
public string ThumbnailUrl { get; set; }
public virtual ICollection<Advertisement> Advertisements { get; set; }
}
DbContext.cs
public class AdvertisingDbContext : DbContext {
public AdvertisingDbContext() : base("Advertising") { }
public DbSet<Advertisement> Advertisements { get; set; }
public DbSet<Photo> Photos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Advertisement>()
.HasMany(x => x.Photos)
.WithMany(y => y.Advertisements)
.Map(m => {
m.ToTable("AdvertisementPhotos");
m.MapLeftKey("AdvertisementID");
m.MapRightKey("PhotoID");
});
}
}