下面新建两个实体,关系为一对一
Product为产品类,WarrantyCard为保修卡类,一个产品对应一个保修卡,一个保修卡对应一个产品。
1、新建实体类
1 public class Product 2 { 3 public int Id { get; set; } 4 public string Name { get; set; } 5 public string Description { get; set; } 6 7 public virtual WarrantyCard WarrantyCard { get; set; } 8 } 9 10 public class WarrantyCard 11 { 12 public int ProductId { get; set; } 13 public DateTime ExpiredDate { get; set; } 14 15 public virtual Product Product { get; set; } 16 }
2、创建EntityContext类并继承DbContext
1 public class EntityContext : DbContext 2 { 3 public EntityContext() 4 : base("name=DBConnectionString") 5 { 6 7 } 8 9 public DbSet<Product> Product { get; set; } 10 public DbSet<WarrantyCard> WarrantyCard { get; set; } 11 12 protected override void OnModelCreating(DbModelBuilder modelBuilder) 13 { 14 modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); 15 base.OnModelCreating(modelBuilder); 16 }
3、在web.config文件中添加数据库连接字符串
1 <connectionStrings> 2 <add name="DBConnectionString" connectionString="Data Source=.;Initial Catalog=OneToOne;Integrated Security=true" providerName="System.Data.SqlClient" /> 3 </connectionStrings>
4、创建表映射类
1 public class ProductMap : EntityTypeConfiguration<Product> 2 { 3 public ProductMap() 4 { 5 ToTable("Product"); 6 HasKey(p => p.Id); 7 8 //两条语句效果一样 9 HasOptional(p => p.WarrantyCard).WithRequired(p => p.Product); 10 //HasRequired(p => p.WarrantyCard).WithRequiredPrincipal(i => i.Product); 11 } 12 } 13 14 public class WarrantyCardMap : EntityTypeConfiguration<WarrantyCard> 15 { 16 public WarrantyCardMap() 17 { 18 ToTable("WarrantyCard"); 19 HasKey(w => w.ProductId); 20 } 21 }
HasOptional(p => p.WarrantyCard).WithRequired(p => p.Product)这句大概意思是:在新增数据到Product表时可以不加数据到WarrantyCard表,也可以加,
但是往WarrantyCard表新增数据时必须有Product表中的ProductId,WarrantyCard依赖Product,生成的是关系是Product表Id是主键,WarrantyCard表ProductId是外键。
5、写点代码测试一下
1 EntityContext db = new EntityContext(); 2 var product = new Product() { Description = "电器", Name = "电磁炉" }; 3 db.Set<Product>().Add(product); 4 db.SaveChanges(); 5 6 var card = new WarrantyCard() { ExpiredDate = DateTime.Now, ProductId = product.Id }; 7 db.Set<WarrantyCard>().Add(card); 8 db.SaveChanges(); 9 10 //WarrantyCard为Product类中的WarrantyCard属性名 11 var list = db.Set<Product>().Include("WarrantyCard").ToList();
6、数据库关系图
时间: 2024-10-07 19:16:25