简体   繁体   English

实体框架5不会使用我的视图

[英]Entity Framwork 5 won't use my view

I created an MVC 4 application using EF (Code First) which mapped to a mixture of tables and views which I created using SQL Management Studio which worked fine. 我使用EF(代码优先)创建了一个MVC 4应用程序,该应用程序映射到使用SQL Management Studio创建的表和视图的混合物,效果很好。

I have started a new MVC 4 project in much the same way as the first, using a completely different database, but this time anytime I try to use a model which maps to a view (not a table), an exception is raised saying that "An object with the name xxx already exists". 我已经使用完全不同的数据库以与第一个项目几乎相同的方式启动了一个新的MVC 4项目,但是这一次我每次尝试使用映射到视图(而不是表)的模型时,都会出现一个异常,说“名称为xxx的对象已存在”。 The SQL profiler shows that EF is trying to create a table for my model. SQL事件探查器显示EF试图为我的模型创建表。

I find that if I drop the views, let EF create the tables from the models, then delete the tables and replace them with view manually, the application will work for about 2 minutes, reading and using the information from my view, but eventually throwing the same exception. 我发现如果放下视图,让EF从模型中创建表,然后删除表并手动将其替换为视图,则该应用程序将运行约2分钟,从我的视图中读取并使用信息,但最终会抛出同样的例外。

I have no idea what is going on here. 我不知道这是怎么回事。

The code that causes the exception is: 导致异常的代码是:

repository.Customers.OrderBy(c => c.AccountNumber);

where the model is: 模型在哪里:

public class Customer
{
    public int Id {get;set;}
    public string AccountNumber {get;set;}
    public string Name {get;set;}
}

OK - the possible cause of this issue is hiding in your context file. 确定-此问题的可能原因隐藏在上下文文件中。 There is probably a statement similar to the one below that is trying to update your database when the model changes. 当模型更改时,可能有一条类似于下面的语句试图更新数据库。

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
    }   

I generally don't use this method. 我通常不使用此方法。 I prefer to delete the database and re-generate it using the package manager console. 我更喜欢删除数据库,然后使用程序包管理器控制台重新生成它。 (Check out the update-database method of the package manager console) (查看程序包管理器控制台的update-database方法)

Using Greg's hint I was able to arrive at the point where I simply added: 使用Greg的提示,我可以到达简单添加的位置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<MyContext>(null);
}

to the context class and this has solved the issue. 到上下文类,这已经解决了问题。 My understanding here is that I have told EF to do no initialisation, essentially having it map to an existing database that is maintained outside of the code first context. 我在这里的理解是,我已经告诉EF不要进行初始化,实质上是让EF映射到在代码优先上下文之外维护的现有数据库。

I have voted up Greg's response as it was the help I needed but creating a new answer as it was the above that solved it eventually. 我赞成Greg的回答,因为这是我需要的帮助,但由于上面的问题最终解决了它,因此创建了一个新的答案。 I hope this was done right. 我希望这做对了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM