5
votes

I recently watched the Domain-Driven Design Fundamentals on Pluralsight by Steve Smith and Julie Lerman, it was a great course, but do I have a question relating to EF Code-First and DDD, I get the concept of rich entities and actually understand most of DDD but I am struggling to understand the use of EF Code-First within DDD. Lets say I have two bounded contexts and I have a Customer entity in each of the bounded contexts sharing an Id and Name.

namespace Accounts
{
    public class Customer : Entity
    {
        public Guid Id { get; private set; }
        public string Name { get; private set; }
        public string AccountNo { get; private set; }
    }
}

namespace Deliveries
{
    public class Customer : Entity
    {
        public Guid Id { get; private set; }
        public string Name { get; private set; }
        public Address DeliveryAddress { get; private set; }
    }
}

In each bounded context I have a data layer with a DbContext, lets for the sake of argument call one Accounts.AccountsDbContext and Deliveries.DeliveriesDbContext (each has a IDbSet, which uses its own bounded context Customer entity as defined above)

My question and what I am struggling to understand is how does one handles code-first migrations across the different DbContext's. The Customer entites refer to the same database table but expose only those properties that are relevant to the bounded context they are in. So how does EF handle this through migrations?

2

2 Answers

2
votes

You need a context in which all fields of the Customer are defined. This context will handle the migrations. You can hide this context from the bounded contexts if desired. You have to disable Migrations for the bounded contexts using

Database.SetInitializer<AccountsContext>(null);

and

Database.SetInitializer<DelivieriesContext>(null);

This information must be present in Julie's course, you have propbably missed it.

There is a good summary of her course. You wil find it in this MSDN magazine article

1
votes

When you use more than one context sharing tables you can't use automatic migrations (I never use them at all). You can generate all migrations and implement it in a single context (it's a manual task but not so hard).

Also, I think that in certain cases you could evaluate a Repository pattern (using multiple repositories and a single context).