Entity Framework - Database First without config

后端 未结 1 1937
滥情空心
滥情空心 2021-01-14 09:25

I\'m developing a class library that deals with an exiting db using EF. I want to avoid the consumer of the class library (and .exe or a web site) to have in the *.config fi

相关标签:
1条回答
  • 2021-01-14 09:56

    There is a constructor on DbContext that takes a DbConnection, and you need to use an EntityConnection object for it:

    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
    
    // Set the properties for the data source.
    sqlBuilder.DataSource = "server name";
    sqlBuilder.InitialCatalog = "database name";
    sqlBuilder.IntegratedSecurity = true;
    
    // Build the SqlConnection connection string.
    string providerString = sqlBuilder.ToString();
    
    var entityBuilder = new EntityConnectionStringBuilder();
    
    // Initialize the EntityConnectionStringBuilder.
    //Set the provider name.
    entityBuilder.Provider = "System.Data.SqlClient";
    
    // Set the provider-specific connection string.
    entityBuilder.ProviderConnectionString = providerString;
    
    // Set the Metadata location.
    entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
    
    using(var context = new YourDbContext(entityBuilder.ToString())){
        //do stuff here
    }
    

    The important thing to note is the metadata part - "Model1" obviously needs to be replaced for your model name.

    Ref: http://msdn.microsoft.com/en-us/library/bb738533.aspx

    EDIT 20/02/2013 22:25

    So as an addition you'll need to extend the created DbContext class with a partial class that adds a constructor to support the above code, like this:

    public partial class YourDbContext
    {
        public YourDbContext(string connection) : base(connection) {}
    }
    

    This class needs to be in the same namespace as the DbContext that is generated by the entity framework wizard.

    0 讨论(0)
提交回复
热议问题