感谢您阅读我的博客,如果您现在工作、学习累了或者疲惫了,不妨聆听一下音乐,它能够减轻你的疲劳,还能够带给您一种舒适愉悦的心情。如果您认为这篇文章还不错或者有所收获,您可以在页面 右侧和底部 扫描二维码 打赏我,您的鼓励是我继续写作、分享的最大动力!

MVC中使用FluentAPI

1.首先引入EF,并在数据库中创建好test1数据库,在配置文件中配置好数据库连接字符串

2.创建实体类
namespace FluentApi
{
    public class Person
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
3.创建数据库上下文对象
using System.Data.Entity;
using System.Reflection;

namespace FluentApi
{
    /// <summary>
    ///     创建数据库上下文对象
    /// </summary>
    public class TestContext : DbContext
    {
        public TestContext() : base("name=conn1")
        {
        }

        public DbSet<Person> Persons { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
        }
    }
}
4.使用FluentAPI配置数据库表
using System.Data.Entity.ModelConfiguration;

namespace FluentApi.EntityConfig
{
    /// <summary>
    ///     使用FluentAPI配置数据库表
    /// </summary>
    public class PersonConfig : EntityTypeConfiguration<Person>
    {
        public PersonConfig()
        {
            ToTable("T_Persons");
            Property(e => e.Name).HasMaxLength(20).IsRequired();
        }
    }
}
5.调用的主程序
using System;
using System.Data.Entity.Validation;

namespace FluentApi
{
    /// <summary>
    ///     使用FluentAPI配置数据库表
    /// </summary>
    internal class Program
    {
        private static void Main()
        {
            Console.Title = "FluentAPI";

            UserFluentApi();

            Console.ReadKey();
        }

        private static void UserFluentApi()
        {
            using (var context = new TestContext())
            {
                var p = new Person
                {
                    Age = 30,
                    Name = "LDH"
                    //Name = "LDH88888888888888888888888888888888888888" // 错误:Name,字段 Name 必须是最大长度为“20”的字符串或数组类型。
                };
                context.Persons.Add(p);

                try
                {
                    context.SaveChanges();
                    Console.WriteLine("创建成功!");
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var err in ex.EntityValidationErrors)
                    foreach (var ve in err.ValidationErrors)
                        Console.WriteLine("错误:" + ve.PropertyName + "," + ve.ErrorMessage);
                }
            }
        }
    }
}
6.生成的数据库表

posted @ 2018-10-24 21:09  Love In Winter  阅读(28)  评论(0编辑  收藏  举报
作者: LifeDecidesHappiness
出处: http://www.cnblogs.com/LifeDecidesHappiness/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址 2468881301@qq.com  联系我,非常感谢。
踏实做一个为人民服务的搬运工!
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能,您的支持和鼓励是我继续写作、分享的最大动力!

点击关注不迷路,让我带你上高速!