温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Entity Framework中怎么使用配置伙伴创建数据库

发布时间:2022-03-03 14:06:40 来源:亿速云 阅读:132 作者:iii 栏目:开发技术

这篇“Entity Framework中怎么使用配置伙伴创建数据库”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Entity Framework中怎么使用配置伙伴创建数据库”文章吧。

EF提供了另一种方式来解决这个问题,那就是为每个实体类单独创建一个配置类。然后在OnModelCreating方法中调用这些配置伙伴类。

创建Product实体类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity.ModelConfiguration; namespace EF配置伙伴.Model {     public class Product     {         public int ProductNo { get; set; }         public string ProductName { get; set; }         public double ProductPrice { get; set; }     } }

创建Product实体类的配置类:ProductMap,配置类需要继承自EntityTypeConfiguration泛型类,EntityTypeConfiguration位于System.Data.Entity.ModelConfiguration命名空间下,ProductMap类如下:

using EF配置伙伴.Model; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; namespace EF配置伙伴.EDM {     public class ProductMap   :EntityTypeConfiguration<Product>     {         public ProductMap()         {             // 设置生成的表名称             ToTable("ProductConfiguration");             // 设置生成表的主键             this.HasKey(p => p.ProductNo);             // 修改生成的列名             this.Property(p =>p.ProductNo).HasColumnName("Id");             this.Property(p => p.ProductName)                 .IsRequired()  // 设置 ProductName列是必须的                 .HasColumnName("Name"); // 将ProductName映射到数据表的Name列         }     } }

在数据上下文Context类的OnModelCreating()方法中调用:

using EF配置伙伴.EDM; using EF配置伙伴.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; namespace EF配置伙伴.EFContext {     public class Context:DbContext     {         public Context()             : base("DbConnection")         { }         public DbSet<Product> Products { get; set; }         protected override void OnModelCreating(DbModelBuilder modelBuilder)         {             // 添加Product类的配置类             modelBuilder.Configurations.Add(new ProductMap());             base.OnModelCreating(modelBuilder);         }     } }

查看数据库,可以看到符合我们的更改:

Entity Framework中怎么使用配置伙伴创建数据库

这种写法和使用modelBuilder是几乎一样的,只不过这种方法更好组织处理多个实体。你可以看到上面的语法和写jQuery的链式编程一样,这种方式的链式写法就叫Fluent API。

以上就是关于“Entity Framework中怎么使用配置伙伴创建数据库”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI