开发者

access EF classes from a Class Library - exactly how do configure/test the connection string in the client? (getting errors)

开发者 https://www.devze.com 2022-12-29 04:59 出处:网络
I\'m getting very confused about how to call my EF classes in a Class Library from the Client Project I have?Things开发者_Go百科 worked fine when they were in the same project.Now I\'m getting errors

I'm getting very confused about how to call my EF classes in a Class Library from the Client Project I have? Things开发者_Go百科 worked fine when they were in the same project. Now I'm getting errors such as "Unable to load the specified metadata resource ".

I've see various ideas / suggestions re how to fix the connection string (e.g. create an App.config in your client project & copy the connection string config from your class library, something about change the connection settings to copy to output, etc)

QUESTION - Can someone provide a solid way on how to get EF class access from a separate project working? (i.e. how to get the correct connection information to the client somehow)

thanks


This worked for me: Create partial class for your generated entities class and add this factory methods:

public partial class DbEntities : DbContext
{
    private DbEntities(string connectionString)
        : base(connectionString)
    {
    }
    public static DbEntities CreateContext()
    {
        return new DbEntities("connection string copied from app.config");
    }
}

Whenever you need to connect to Db, use DbEntities.CreateContext(). "new DbEntities()" will not work, because it will try to read connection string from config file.

You can delete the default constructor "DbEntities()" from generated file or edit the generated file and put the connection string instead of "name=DbEntities":

public DbEntities() : base("name=DbEntities") { }

but this file will be recreated when you update your db model.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号