问题
In ELMAH for logging errors to the database you can write:
<errorLog type="Elmah.SqlErrorLog, Elmah"
connectionStringName="EducoparkEntities"/>
However, if I use EntityFramework, this doesn't work because the connection string for EF contains metadata as well:
<add name="EducoparkEntities" connectionString="metadata=res://*/EducoparkData.csdl|res://*/EducoparkData.ssdl|res://*/EducoparkData.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(Local);Initial Catalog=...;User Id=...;Password=...;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
So, how can I use the EntityFramework connection string in Elmah?
回答1:
1
You can extract the database connection string via the ConnectionStringBuilder provided in the entity framework.
private string ExtractConnectionStringFromEntityConnectionString(string entityConnectionString)
{
// create a entity connection string from the input
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(entityConnectionString);
// read the db connectionstring
return entityBuilder.ProviderConnectionString;
}
2
To plug that db connection string into Elmah you will have to set it on Application_Start ( in Global.asax)
回答2:
public class YourErrorLog : SqlErrorLog
{
public override string ConnectionString
{
get
{
//return any Connection string EF or any
}
}
}
and modify configuration
<elmah>
<errorLog type="YourAssembly.YourErrorLog, YourAssembly" connectionStringName="elmah-sqlserver" />
</elmah>
Elmah will ask sql Connection string but when it need will get your connection string.
回答3:
You cannot - at least not directly. What you'd need to do is extract the part of the EF connection string that really references the database (the provider connection string
), and put that into it's own entry in the <connectionStrings>
section of your web.config:
<connectionStrings>
<add name="EducoparkELMAH"
connectionString="Data Source=(Local);Initial Catalog=...;User Id=...;Password=...;MultipleActiveResultSets=True"
provider="System.SqlClient" />
</connectionStrings>
Or you could do it programmatically - the entity context will have a property called "Connection", which in turn has a property "ConnectionString", which is the one you're looking for:
string elmahConnectionString = EducoparkEntities.Connection.ConnectionString;
Marc
回答4:
You can use Elmah.Contrib.EntityFramework nuget package for this purpose.
(Disclaimer: I wrote it)
来源:https://stackoverflow.com/questions/1083558/how-to-use-entityframework-connection-string-for-elmah