C# Interactive and Entity Framework

丶灬走出姿态 提交于 2019-12-06 16:38:21

Struggled with this one for a while before I finally got it working.

Create a new partial class (for example named YourEntities.cs) with a new overload for your constructor that takes a connection string parameter (don't modify your existing class as it will be overwritten whenever you re-model the database):

using System.Data.Entity;

namespace YourNamespace.Models
{
    public partial class YourEntities : DbContext
    {
        public YourEntities(string connectionString)
            : base(connectionString)
        {
        }
    }
}

Then, build your project, right click it and click "Initialize Interactive with Project". Open your web.config / app.config and copy the connection string to your clipboard.

In the interactive window, paste this replacing ConnStringHere with your connection string but don't hit enter:

var db = new YourNamespace.Models.YourEntities("ConnStringHere");

After you paste, replace " in the connection string with \" , go to the end of the line in C# interactive and hit enter.

Then you should be able to use db in your C# Interactive window it as if it were in your app:

Print(db.Employees.Count());

I realize this is old, but I found a way to make this work without changing my code, or creating any proxies or other work-around code. I was able to make this work by editing the config file for the interactive window, itself. See my answer in this post:

Project can't find my EF connection string in C# Interactive

You may have to add other config data, as well, if your app relies on it. Just adding the connection string was enough, for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!