Question

I'm currently working on an MVC-project that should be highly modular. For example I want to have a user-module, a menu-module and a page module.

Because the modules need to be highly re-usable in different visual studio solutions I create separate projects for each module.

For the database mapping I would like to make use of the entity framework. I've created a separate DbContext in each module-project. Each DbContext contains the entities associated with the module.

Unfortunately I'm not able to let EF create foreign keys between entities in different modules/dbContexts.

For example: Core module contains User-Entity Page module contains Page-Entity which has an author that links to the User-entity defined in the core-module dbContext.

Has anyone an idea how I can create foreign keys across modules/dbContexts?

Was it helpful?

Solution

Are all of your entities in the same database? I would suggest separating your assemblies like this:

Data - project containing your Entity Framework model and/or class/entity definitions (depending on which type of EF approach you are using).

Service - project containing interfaces and classes that manipulate your data. Example, for your User entity (and related items), you might have this:

public interface IUser : IDisposable
{
    Data.User Get(int userId);
    IQueryable<Data.User> GetAll();
    //other method definitions for User entity CRUD
}

Then, you implementation:

public class User : IUser
{
    private readonly DataEntities _dataContext = new DataEntities(); //this is from your EF Data assembly

    public Data.User Get(int userId)
    {
        return _dataContext.Users.FirstOrDefault(u => u.UserId == userId);
    }

    public IQueryable<Data.User> GetAll() 
    {
        return _dataContext.Users;
    }

    //other method implementations

    public void Dispose()
    {
        _dataContext.Dispose();
    }
}

Then, reference both your Service and Data assemblies in your module projects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top