Entity Framework使用Fluent API配置案例

2022-04-18 09:13:36

一、配置主键

要显式将某个属性设置为主键,可使用 HasKey 方法。在以下示例中,使用了 HasKey 方法对 Product 类型配置 ProductId 主键。

1、新加Product类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace FluentAPI.Model{    public class Product    {        public int ProductId { get; set; }        public string ProductName { get; set; }        public decimal Price { get; set; }    }}

2、新建ProductMap类,用来设置主键

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.Entity;using System.Data.Entity.ModelConfiguration;using FluentAPI.Model;namespace FluentAPI.Da;namespace FluentAPI.Data.FluentAPIMap{    public class CourseMap : EntityTypeConfiguration<Course>    {        public CourseMap()        {            /*可以使用点表示法访问复杂类型的属性。              设置Course类里面的Department属性的Name的最大长度是32             */            this.Property(p => p.Department.Name).HasMaxLength(32);        }    }}

十一、将CLR 实体类型映射到数据库中的特定表

/*Department 的所有属性都将映射到名为 t_ Department 的表中的列。*/ToTable("t_Department");/*您也可以这样指定架构名称:*/ToTable("t_Department", "school");

代码地址:点此下载

到此这篇关于Entity Framework使用Fluent API配置案例的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。