asp.netdatabaseentity-framework-4objectcontextobjectset

Attach additional ObjectSets to ObjectContext from separate project


I hope this makes sense. I have a ASP.NET web application that uses Entity Framework. I have added a couple of custom tables to the db and created a separate project to handle the CRUD operations for those tables. I chose the separate project because I don't want future upgrades to the application to overwrite my custom features.

My problem is this. How do I attach/combine my custom ObjectContext to the ObjectContext of the application? I want to use the same UnitOfWorkScope (already in the application) to maintain the one ObjectContext instance per HTTP request. Again, I don't want to add my ObjectSets to the application's ObjectContext for my reason listed above.

Here is some code:

Widget.cs

public partial class Widget
{
public Widget()
{
}
public int WidgetId {get;set;}
public string WidgetName {get;set;}
}

WidgetObjectContext.cs

public partial class WidgetObjectContext : ObjectContext
{
private readonly Dictionary<Type, object> _entitySets;

public ObjectSet<T> EntitySet<T>()
where T : BaseEntity
{
var t = typeof(T);
object match;
if(!_entitySets.TryGetValue(t, out match))
{
match = CreateObjectSet<T>();
_entitySets.Add(t, match);
}
return (ObjectSet<T>)match;
}

public ObjectSet<Widget> Widgets
{
get
{
if((_widgets == null))
{
_widgets = CreateObjectSet<Widget>();
}
return _widget;
}
}
private ObjectSet<Widget> _widgets;

In my WidgetManager class if I was using the application's ObjectContext I would query my tables like this:

var context = ObjectContextHelper.CurrentObjectContext;
var query = from c in context.ObjectSet .... etc

What I want would be to do something like this:

var context = ObjectContextHelper.CurrentObjectContext.Attach(WidgetObjectContext);

I know this won't work but that is the gist of what I am trying to accomplish. Hope this is clear enough. Thanks.


Solution

  • I don't think it is possible. ObjectContext creates entity connection which connects to metadata describing mapping and database. But you have to different sets of metadata - one for ASP.NET application and one for separate project. Simply you need two connection to work with these models => you need two ObjectContexts.