Entity Framework Power Tools安装和使用

Entity Framework Power Tools是一个由EntityFramework开发小组提供的工具,它可以从现有数据库生成Fluent款式的Code First代码。

大致来说,这个工具有这样几个功能:
1) 按照现有数据库结构,生成Code First POCO class、DbContext class和相应的mapping class。

2) 以designer模式或XML模式查看POCO class对应的Entity Data Model (edmx) 。

3) 查看Entity Data Model所对应的DDL。

4) 生成EF Generated View提高EF性能。

Entity Framework Power Tools安装

1、VS-工具-扩展管理器-搜索:Entity Framework Power Tools-然后安装

2、安装完成后,然后重启VS

在项目上单击右键,在弹出的菜单中可以看到增加了一个Entity Framework的菜单项,里面有一个Reverse Enginner Code First。单击它以后出现选择数据连接的窗口,建立好数据连接之后它会自动地生成所有数据表所映射的实体类和对应的映射类(放在Mapping文件夹中),并且还自动生成了DbContext类。用生成的这些类取代原来通过EF直接建立的实体类和Context,强大吧。

3、Entity Framework Power Tools生成的部分代码

model news

using System;
using System.Collections.Generic;

namespace Web.Models
{
    public partial class news
    {
        public int ID { get; set; }
        public string title { get; set; }
        public string cons { get; set; }
        public int counts { get; set; }
        public System.DateTime times { get; set; }
    }
}

model admin

using System;
using System.Collections.Generic;

namespace Web.Models
{
    public partial class admin
    {
        public int ID { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public Nullable<System.DateTime> logintimes { get; set; }
    }
}

DbContext

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Web.Models.Mapping;

namespace Web.Models
{
    public partial class mvc_ceshi1Context : DbContext
    {
        static mvc_ceshi1Context()
        {
            Database.SetInitializer<mvc_ceshi1Context>(null);
        }

        public mvc_ceshi1Context()
            : base("Name=mvc_ceshi1Context")
        {
        }

        public DbSet<admin> admins { get; set; }
        public DbSet<news> news { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new adminMap());
            modelBuilder.Configurations.Add(new newsMap());
        }
    }
}

 web.config也会生成链接字符串

4、新建类库注意事项

1. 如果是新建的类库需先引用Entity Framework.dll,不然如图异常
2. 链接数据库的时候没有在“高级设置”中设置“安全连接”,如图异常
异常图(参数错误。(异常来自HRESULT:0x80070057(E_INVALIDARG))):

 

MSDN:https://msdn.microsoft.com/zh-CN/data/jj593170

 

posted @ 2016-07-14 08:47  WebApi  阅读(4919)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI