EntityFramework:FluentAPI基本配置

1.数据库建表 sys_user

USE [ef_test]
GO

/****** Object:  Table [dbo].[sys_user]    Script Date: 2018/12/23 22:21:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[sys_user](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [UserName] [varchar](50) NOT NULL,
    [Age] [bigint] NULL,
    [CreateDateTime] [datetime] NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

2.创建User类

using System;


namespace FluentAPI
{
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public int? Age { get; set; }
        public int? Age2 { get; set; }
        public DateTime CreateDateTime { get; set; }
    }
}

3.创建一个UserMap配置类

配置过程中尽量用约定,EF配置越少越好。

using System.Data.Entity.ModelConfiguration;

namespace FluentAPI
{
    public class UserMap : EntityTypeConfiguration<User>
    {
        public UserMap()
        {
            this.ToTable("sys_user");

            //EF默认主键为Id,可不写
            this.HasKey(x => x.Id);

            //该字段不参加映射数据库
            this.Ignore(x => x.Age2);

            //HasMaxLength 设定字段的最大长度
            //IsRequired() 属性不能为空 IsOptional (属性可以为空,没什么用)
            this.Property(p => p.UserName).HasMaxLength(32).IsRequired();
            this.Property(p => p.Age).IsOptional();

            //是否对应固定长度 IsFixedLength
            //this.Property(p => p.UserName).IsFixedLength();

            //对应的数据库类型是varchar 而不是  nvarchar
            //this.Property(p => p.UserName).IsUnicode(false);

            // CreateDateTime 列对应数据库中名字为Create_Date的字段
            //this.Property(p => p.CreateDateTime).HasColumnName("Create_Date");

            //指定字段是自动增长类型
            this.Property(p => p.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
        }
    }
}

4.创建一个DbContext类

using System.Data.Entity;
using System.Reflection;

namespace FluentAPI
{
    public class FluentAPIContext : DbContext
    {
        public FluentAPIContext() : base("name=Conn") { }

        public virtual DbSet<User> User { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //加载当前代码程序集所有继承EntityTypeConfiguration
            modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());

            //加载其他程序集继承EntityTypeConfiguration
            //modelBuilder.Configurations.AddFromAssembly(Assembly.Load("Lilb.Model"));

            //单独加载配置类
            //modelBuilder.Configurations.Add(new UserMap());

            //直接在OnModelCreating进行配置
            //modelBuilder.Entity<User>().ToTable("sys_user");
        }
    }
}
原文地址:https://www.cnblogs.com/lilb/p/10166014.html