My WCF Data Service works great when I fetch data from it. When I try to insert new data, I get the following exception:
The ConnectionString property has not been initialized
The only thing I modified is to use my partial class that tells to use the connection string name:
public MyExtEntities(string connectionString) : base(connectionString) { ... } : base(connectionString) { ... }
And I overrode the CreateDataSource
, so always have the proper context:
protected override MyExtEntities CreateDataSource()
{
MyExtEntities entities = null;
try
{
entities = new MyExtEntities ("name=MyExtEntities");
...
return entities;
And you can believe, the config file contains that key:
add name="MyExtEntities " connectionString="metadata=res://*...
The stack shows that the core system is running, nothing from my methods:
System.Data.EntityClient.EntityConnection.Open()
at: System.Data.Objects.ObjectContext.EnsureConnection()
at: System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at: System.Data.Entity.Internal.InternalContext.SaveChanges()
at: System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at: System.Data.Entity.DbContext.SaveChanges()
at: lambda_method(Closure , Object )
at: System.Data.Services.Providers.DbContextHelper.<>c_DisplayClass4.b_0()
at: System.Data.Services.Providers.ObjectContextServiceProvider.SaveContextChanges()
at: System.Data.Services.Providers.ObjectContextServiceProvider.SaveChanges()
at: System.Data.Services.Providers.EntityFrameworkDataServiceProvider.SaveChanges()
at: System.Data.Services.DataService1.HandleNonBatchRequest(RequestDescription description) <br> at: System.Data.Services.DataService
1.HandleRequest()
I already added this to OnStartProcessingRequest
:
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
if (this.CurrentDataSource == null)
this.CreateDataSource();
base.OnStartProcessingRequest(args);
}
It's really strange that the fetching works and it uses the same connection... What should I check?
Well, to fix the unexplainable, here is a way.
For an unknown reason, when the CreateDataSource method creates a new DbContext instance, it doesn't always have a Connection String. To prevent this from happenning, I created a DbContext instance along with the DataService class to ensure that I have a proper instance:
public class InformationDataService : DataService<InformationEntities>
{
private InformationEntities context = new InformationEntities("name=InformationEntities");
After that I modified the overriden CreateDataSource to always return the initially created (and hopefully properly working) DbContext:
protected override InformationEntities CreateDataSource()
{
if (context == null)
return new InformationEntities("name=InformationEntities");
return context;
}
After these modifications, the error is gone.