This is a default EF ObjectContext factory, perfect when using POCOs
public interface IObjectContextFactory
{
ObjectContext Create();
ObjectContext Create(string connectionString);
}
public class DefaultObjectContextFactory : IObjectContextFactory
{
public ObjectContext Create()
{
return this.Create(ConfigurationManager.ConnectionStrings["AspenConnectionString"].ConnectionString);
}
public ObjectContext Create(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString");
var connection = new SqlConnection(connectionString);
var workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { GetModelMappingConfigurationAssembly() });
CheckAndBeSureMetadataIsLoaded(workspace);
return this.Create(new EntityConnection(workspace, connection));
}
private ObjectContext Create(EntityConnection con)
{
if (con == null)
throw new ArgumentNullException("con");
return new ObjectContext(con);
}
private static void CheckAndBeSureMetadataIsLoaded(MetadataWorkspace workspace)
{
Debug.Assert(workspace.GetItemCollection(DataSpace.CSpace).GetItems<EntityType>().Count != 0);
Debug.Assert(workspace.GetItemCollection(DataSpace.SSpace).GetItems<EntityType>().Count != 0);
}
private Assembly GetModelMappingConfigurationAssembly()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = assemblies.Where(a => a.FullName.Contains("EntityMapping")).SingleOrDefault();
if (assembly == null)
throw new MappingException("Can't find the Assembly with the Entity Configuration Mapping");
return assembly;
}
}
Note: The GetModelMappingConfiguration will look through all referenced assemblies for a separate assembly where the EDMX file is located. Can probably be done much better, any suggestions?
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


1.34k
0




Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'