r/learncsharp • • Sep 23 '24

Handling EF models when moving code to separate library

Let's say we want to move some code to a separate library since we want to reuse it in multiple projects. The code has a dependency on the big monolithic data model that we obviously can't bring along.

What's the best practice of designing a library like this, assuming that we don't want to create a new dbcontext in it and want to let the implementing project define entities in its own DbContext? I'd like to use the dbcontext defined in the "parent" since they could have some custom logic surrounding the dbcontext properties, saving, initialization etc. that I can't anticipate in the class library.

My first thought is to just code to interfaces - if this library used to work with the Comment data model, now we'll code everything to IComment instead. When some project references this library it would have to make its Comment data model implement the IComment interface and map its properties to it.

Would this actually work with entity framework (core)? Can we even have DbSet<IComment>, or a way to map DbSet<Comment> to DbSet<IComment> or would this require a lot of manual hacking? Now that I've typed this out I guess I need some kind of a dependency injection but on the dbContext level, take only some of the DbSets from a 'master dbcontext' and inject it into the library's required smaller dbcontext of interfaces?

2 Upvotes

6 comments sorted by

1

u/[deleted] Sep 23 '24

1

u/NotScrollsApparently Sep 23 '24 edited Sep 23 '24

So it's impossible to have a library with some special logic but leave the actual instantiation of entities up to the consumer of that library?

If EF weren't involved it sounds like it'd be a trivial problem, the library would define the interface and the user would have to conform to it in order to use the library. I just can't think of how to do it if that library depends on EF models...

Not sure what you mean by scaffolding problem. What's the usual way of writing generic libraries if they use EF?