首页 > 代码库 > 将一个实体数据保存到不同的数据表中<EntityFramework6.0>
将一个实体数据保存到不同的数据表中<EntityFramework6.0>
2014-11-22声明方式
1 public class Product 2 { 3 [Key] 4 [DatabaseGenerated(DatabaseGeneratedOption.None)] 5 public int SKU { get; set; } 6 public string Description { get; set; } 7 public decimal Price { get; set; } 8 public virtual string ImageURL { get; set; } 9 }10 11 public class ProductContext : DbContext12 {13 public DbSet<Product> Products { get; set; }14 protected override void OnModelCreating(DbModelBuilder modelBuilder)15 {16 base.OnModelCreating(modelBuilder);17 modelBuilder.Entity<Product>()18 .Map(m =>19 {20 m.Properties(p => new {p.SKU, p.Price, p.Description});21 m.ToTable("Table1");22 }).Map(m =>23 {24 m.Properties(p => new {p.SKU, p.ImageURL});25 m.ToTable("Table2");26 });27 }28 }
怎么使用
1 static void Main(string[] args) 2 { 3 using (var context=new ProductContext()) 4 { 5 6 var products = new List<Product> 7 { 8 new Product {SKU = 1, Price = 12.1m, Description = "1test", ImageURL = "1.jpg"}, 9 new Product {SKU = 2, Price = 12.2m, Description = "2test", ImageURL = "2.jpg"},10 new Product {SKU = 3, Price = 12.3m, Description = "3test", ImageURL = "3.jpg"},11 new Product {SKU = 4, Price = 12.4m, Description = "4test", ImageURL = "4.jpg"},12 new Product {SKU = 5, Price = 12.5m, Description = "5test", ImageURL = "5.jpg"},13 new Product {SKU = 6, Price = 12.6m, Description = "6test", ImageURL = "6.jpg"}14 }; 15 context.Products.AddRange(products);16 context.SaveChanges();17 }18 using (var context = new ProductContext())19 {20 foreach (var product in context.Products)21 {22 Console.WriteLine("{0}--{1}--{2}--{3}", product.SKU, product.Price, product.Description,23 product.ImageURL);24 }25 Console.ReadKey();26 }27 }
生成表结构
运行效果
将一个实体数据保存到不同的数据表中<EntityFramework6.0>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。