一、单实体对应多表
适用场景主表,拥有相同主键附属表或扩展表。
1、 建表词句
CREATE TABLE [Chapter2].[Product](
[SKU] [int] primary key ,
[Description] [varchar](50) NOT NULL,
[Price] [decimal](18, 2) NOT NULL) CREATE TABLE [Chapter2].[ProductWebInfo](
[SKU] [int] primary key ,
[ImageURL] [varchar](1024) NULL
)
2、新建控制程序,添加EntityFramework 引用。
3、创建Product实体,实体包含两个表组合字段
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int SKU { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string ImageURL { get; set; }
}
4、新建DbContext子类,注意连接字符串。
public class ProductContext: DbContext
{
public DbSet<Product> Products { get; set; } public ProductContext() : base("EFRecipesEntities")
{ } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Product>()
.Map(m =>
{
m.Properties(p => new { p.SKU, p.Description, p.Price });
m.ToTable("Product", "Chapter2");
})
.Map(m =>
{
m.Properties(p => new { p.SKU, p.ImageURL });
m.ToTable("ProductWebInfo", "Chapter2");
});
}
}
注意代码中,Map方法,由多个表组合成单个类配置。
5、修改控制台程序代码
static void Main(string[] args)
{
using (var context = new ProductContext())
{
var product = new Product
{
SKU = ,
Description = "Expandable Hydration Pack",
Price = 19.97M,
ImageURL = "/pack147.jpg"
};
context.Products.Add(product);
product = new Product
{
SKU = ,
Description = "Rugged Ranger Duffel Bag",
Price = 39.97M,
ImageURL = "/pack178.jpg"
};
context.Products.Add(product);
product = new Product
{
SKU = ,
Description = "Range Field Pack",
Price = 98.97M,
ImageURL = "/noimage.jp"
};
context.Products.Add(product);
product = new Product
{
SKU = ,
Description = "Small Deployment Back Pack",
Price = 29.97M,
ImageURL = "/pack202.jpg"
};
context.Products.Add(product);
context.SaveChanges();
}
using (var context = new ProductContext())
{
foreach (var p in context.Products)
{
Console.WriteLine("{0} {1} {2} {3}", p.SKU, p.Description,
p.Price.ToString("C"), p.ImageURL);
}
} Console.ReadKey();
}
运行使用SQLProfile查看查询执行语句及结果。
总结:单实体多表时,重写DbContext字类,OnModelCreating方法,在方法中映射(注册)实体属性使用哪些表字段填充。