How to use EntityFramework connection string for Elmah?

陌路散爱 提交于 2019-12-19 06:28:09

问题


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=&quot;Data Source=(Local);Initial Catalog=...;User Id=...;Password=...;MultipleActiveResultSets=True&quot;" 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

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