代码优先实体框架未在数据库中创建表 [英] Code First Entity Framework not creating tables in the database

查看:133
本文介绍了代码优先实体框架未在数据库中创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用Code First Entity Framework 4.1创建了一个简单的类库.

数据库连接位于控制台应用程序app.config中,连接字符串的名称为"default".
所以我像这样初始化了DbContext -

I just created a simple class library using Code First Entity Framework 4.1.

The db connection is in the console applcations app.config and the name of the connectionstring is "default".
So i initialized the DbContext like this -

public class EmployeeContext : DbContext
    {
       public EmployeeContext() : base("name=default") { }
        public List<employee> Employees { get; set; }
    }


我已经在控制台应用程序中引用了类库.然后尝试添加一个employee.


I have referenced the Class Library in the console application. Then just try to add one employee.

class Program
    {
        static void Main(string[] args)
        {
            createEmp();
        }
 
        static void createEmp()
        {
            var obj = new EmployeeContext();
            Employee emp = new Employee();
            emp.ID = 1;
            emp.Name = "Test";
            obj.SaveChanges();
        }
    }


没有错误,但是未在数据库中创建表.

当我查看employeecontext时,会看到此异常-
ServerVersion''(((((System.Data.Entity.DataContext)(obj)).Database.Connection).ServerVersion''引发了类型为``System.InvalidOperationException''字符串的异常{System.InvalidOperationException}
连接已关闭
.

这是我第一次接触代码优先实体框架.

任何人有什么错的想法吗?


There is no error but the tables are not created in database.

When I look into the employeecontext, I see this exception -
ServerVersion ''(((System.Data.Entity.DataContext)(obj)).Database.Connection).ServerVersion'' threw an exception of type ''System.InvalidOperationException'' string {System.InvalidOperationException}
The connection is closed
.

This is my first hands on with code first entity framework.

Anyone has any idea of what is wrong?

推荐答案

您的代码有两个大问题.我强烈建议您观看或阅读有关使用Code First和EF的介绍性材料.在msdn(msdn.com/data/ef)上,您可以首先在代码上找到一些简短的介绍性视频.

问题1:在dbcontext中,Employees必须是DbSet< Employee>.使EF能够与员工数据进行交互.

问题2:代码优先"将在EF需要首次访问数据库时初始化数据库.但是将没有数据库访问权限,因为您已经创建了员工,但是obj(上下文)不知道它.

在obj.SaveChanges之前,添加新员工,以便obj通过以下方式了解它:

obj.Employees.Add(emp);
There are two big problems with your code. I highly recommend that you watch or read some intro material on using Code First and EF. On msdn (msdn.com/data/ef) you can find some short intro videos on code first.

Problem #1: in the dbcontext, Employees must be a DbSet<Employee> for EF to be able to interact with the employee data.

Problem #2:Code First will initialize the database the first time EF needs to access it. But there will be no db access because you''ve created the employee but the obj (context) is unaware of it.

Before obj.SaveChanges, add the new employee so that the obj is aware of it with:

obj.Employees.Add(emp);


这篇关于代码优先实体框架未在数据库中创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆