I'm trying to use DDD with EFCore and I am struggling to find a way to map 2 POCOs from different context that represent the same entity to the same table.
I have a User class inside UserContext, with all the properties needed to create a new user to my application.
And I have either a User class inside my OrderContext, in this class I only have the Id and Email properties, cause it's all that is needed in OrderContext to work.
So I have something like this:
modelBuilder.Entity<Domain.UserContext.User>(u =>
{
u.ToTable("User").HasKey(e => e.Id);
u.OwnsOne(e => e.Name);
u.OwnsOne(b => b.HomeAddress);
});
modelBuilder.Entity<Domain.OrderContext.User>(u =>
{
u.ToTable("User").HasKey(e => e.Id);
});
modelBuilder.Entity<Domain.OrderContext.Order>(p =>
{
p.ToTable("Order").HasKey(b => b.Id);
p.HasOne(x => x.User); // this is OrderContext.User
});
I can't seem to find a way to map both User classes to the same table. Is there a way to do it?
Edit1: Both contexts are bounded context DDD's concept not DbContext.
I just need both classes to be maped as the same table. The Add-Migration command return a message telling me that it cannot map 'OrderContext.User' to table 'User' since it is already mapped to 'UserContext.User'.
The main cause of issue is, EF Core cannot figure out how to use same table for 2 different entities. There is lack of data in mapping, once you fill that in, it works as expected.
First you will need to define how are they related to each other. Sharing same table with same PK does not have Foreign Key defined on server side but there is still intrinsic relationship between both entities which is one-to-one and using PK as FK. Once you define relationship, you will see that it works and both entities are mapped to same table. (Just like how owned entities are mapped to same table). This may not be end of mapping for your case though. Since from EF perspective they are still 2 different entities, except for Id (or PK property), they will have own columns to store data. But what if you have columns which are common in both the context (like Email in your scenario). In such case, you would need to provide mapping for those additional column too. If you map them to same column explicitly, they will start sharing the column in database. Overall the code would look like this.
namespace UserContext
{
public class User
{
public int Id { get; set; }
public string Email { get; set; }
// Other properties
}
}
namespace OrderContext
{
public class User
{
public int Id { get; set; }
public string Email { get; set; }
}
}
// In OnModelCreating method
modelBuilder.Entity<UserContext.User>(u =>
{
u.ToTable("User");
u.Property(e => e.Email).HasColumnName("Email");
// Configuration for other properties
});
modelBuilder.Entity<OrderContext.User>(u =>
{
u.ToTable("User");
u.Property(e => e.Email).HasColumnName("Email");
u.HasOne<UserContext.User>().WithOne().HasForeignKey<OrderContext.User>(e => e.Id);
});
Above code creates single table with shared columns and should work as expected. You can add more entities in the same table if you want by following same configuration. Here, I used User from UserContext as principal side but you can use any side. The main reasoning for me was, UserContext.User will be the entity which will be added when adding new User. Entities sharing the table do not have to be subset either. But there will be columns for additional properties which are not shared.
#Smit provided solution should work, but it is not ideal for isolated bounded contexts, where each of them is not aware of one another and each is taking care of it's own configurations.
I have solved this problem by adding separate DbContexts for each bounded context. Each of these contexts inherit base DbContext, where I have my shared logic (like auditing, etc.), and each DbContext inside bounded contexts has it's own DbSets and Fluent Api configurations. This way I have entities which point to the same table, but from different DbContexts.
I am looking at this problem myself. I noticed, that if you specify schema name for one of the tables then EF will not complain.
For example in your case:
modelBuilder.Entity<Domain.UserContext.User>(u =>
{
u.ToTable("User", "dbo").HasKey(e => e.Id);
u.OwnsOne(e => e.Name);
u.OwnsOne(b => b.HomeAddress);
});
modelBuilder.Entity<Domain.OrderContext.User>(u =>
{
u.ToTable("User").HasKey(e => e.Id);
});
Of course this is not a full solution and even not a workaround, since you can not have more than 2 mentions of "User" table (that is, in more than 2 contexts).
Also i found https://data.uservoice.com/forums/72025-entity-framework-core-feature-suggestions/suggestions/1872001-map-multiple-entities-to-same-table which makes me think that this in general is not possible.
Regarding DDD in general
Most sources say that your bounded contexts should be isolated not only by code, but also by data. This in theory means, that your User table should be duplicated in each bounded context. This is ideal way, but is unnecessarily complex (imho) for more simple scenarios, since it involves data synchronization across all duplicated tables.
Related
I'm not sure if this relationship has a name, so maybe I'm just missing it. I didn't find anything in the docs that looked like this.
I have a many-to-one relationship, sort of, but only one relationship matters, so it's kind of a one-to-one, but on a condition at the many side.
Equipment has many Contracts, but at most one active Contract.
Contract always has one Equipment, and has a reference to the Equipment. That side works just fine. I have business logic to prevent more than one Contract for an Equipment being active.
public class EquipmentModel{
public int Id {get; set;}
//...other properties
}
public class ContractModel{
public int Id {get;set;}
public EquipmentModel Equipment {get;set;}
public bool Active {get;set;}
//...other properties
}
This means I can do a _contracts.Include(x => x.Equipment) and get the equipment entity for the contract.
But I can't wrap my head around the relationship the other direction. I don't want to just put all the Contacts on the Equipment entity, I don't have a need for them and it seems like overkill.
I suppose I could put the Contract entity on the Equipment model and manually manage the relationship in business logic, but I'm hoping Entity Framework has a better way to designate this.
I could also pull back all contracts and use some business logic to filter down to the active one, but that's also less than ideal.
public IEnumerable<ContractModel> Contracts {get;set;}
Ideally, I'd want to be able to do something like _equipment.Include(x => x.ActiveContract) and have the one Contract with an Active == true automatically. Is this a pattern that exists within EF Core?
The easiest way with that design is to use a Filtered Include,
_equipment.Include(x => x.Contracts.Where(c => c.Active))
You can reuse this expression by creating a method on your DbContext, that returns the base query with the Include, eg
public IQueryable<Equipment> GetEquipment() => this.Set<Equipment>().Include(x => x.Contracts.Where(c => c.Active));
Which can be further filtered by the calling code before running the query, eg
var equips = db.GetEquipment().Where(e => e.Name == equipName).ToList();
If you feel strongly about it you can even omit the DbSet<Equipment> property on the DbContext (registering Equipment as an Entity in OnModelCreating), and replace it with
public IQueryable<Equipment> Equipment => this.Set<Equipment>().Include(x => x.Contracts.Where(c => c.Active));
I'm learning Entity Framework Core. I came across the term "Owned Entity" in almost all tutorials.
Here is one example on using an Owned Entity in Entity Framework Core
Job Entity:
public class Job : Entity
{
public HiringManagerName HiringManagerName { get; private set; }
}
HiringManagerName Value Object:
public class HiringManagerName : ValueObject
{
public string First { get; }
public string Last { get; }
protected HiringManagerName()
{
}
private HiringManagerName(string first, string last)
: this()
{
First = first;
Last = last;
}
public static Result<HiringManagerName> Create(string firstName, string lastName)
{
if (string.IsNullOrWhiteSpace(firstName))
return Result.Failure<HiringManagerName>("First name should not be empty");
if (string.IsNullOrWhiteSpace(lastName))
return Result.Failure<HiringManagerName>("Last name should not be empty");
firstName = firstName.Trim();
lastName = lastName.Trim();
if (firstName.Length > 200)
return Result.Failure<HiringManagerName>("First name is too long");
if (lastName.Length > 200)
return Result.Failure<HiringManagerName>("Last name is too long");
return Result.Success(new HiringManagerName(firstName, lastName));
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return First;
yield return Last;
}
}
Entity Configuration:
public class JobConfiguration : IEntityTypeConfiguration<Job>
{
public void Configure(EntityTypeBuilder<Job> builder)
{
builder.OwnsOne(p => p.HiringManagerName, p =>
{
p.Property(pp => pp.First)
.IsRequired()
.HasColumnName("HiringManagerFirstName")
.HasMaxLength(200);
p.Property(pp => pp.Last)
.IsRequired()
.HasColumnName("HiringManagerLastName")
.HasMaxLength(200);
});
}
}
And this gets created as two columns in table like other columns in Job Entity.
Since this is also created as columns just like other properties in entity this can directly be added as normal properties in the Job Entity. Why this needs to be added as Owned Entity?
Please can anyone help me understand,
What is owned entity?
Why we need to use owned entity?
When to use owned entity?
What does this look like without owned entities?
If you create an entity, Job, in EF Core that points to a complex object, HiringManagerName, in one of the properties, EF Core will expect that each will reside in a separate table and will expect you to define some sort of relationship between them (e.g. one-to-one, one-to-many, etc.).
When retrieving Job, if you want to explicitly load the values of HiringManagerName as well, you'd have to use an explicit Include statement in the query or it will not be populated.
var a = dbContext.Jobs
.Include(b => b.HiringManagerName) //Necessary to populate
.ToListAsync();
But because each is thought to be a separate entity, they will be required to expose keys and you'll have to configure foreign keys between each.
What is an owned entity?
That's where [Owned] types come in (see docs). By marking the child class with the [Owned] attribute, you leave the explicit handling of that relationship to EF Core to manage and no longer have a need to define the key(s)/foreign key(s) on the owned type. Same if you point to a collection of your owned type - you no longer need to deal with navigation properties on either class to describe the relationship.
EF Core also supports queries against these owned types, as in:
var job = context.Jobs.Where(a => a.HiringManagerName.First == "fingers10").FirstOrDefaultAsync();
Now, it comes with two important design restrictions described in the docs (but elaborated on here):
You cannot create a DbSet for the owned type
This means that you cannot subsequently do a DB call with:
dbContext.HiringManagerNames.ToListAsync();
This will throw because you are expected to simply retrieve the value as part of a call to:
dbContext.Jobs.ToListAsync();
Unlike the first example I gave, HiringManagerNames no longer needs to be explicitly included and will instead be returned with a call to the Jobs DbSet<T>.
Cannot call Entity<T> with an owned type on ModelBuilder
Similarly, you cannot reference your owned type in the ModelBuilder to configure it. Rather, if you must configure it, do so through the configuration against your Jobs entity and against the owned property, e.g.:
modelBuilder.Entity<Job>().OwnsOne(a => a.HiringManagerNames).//Remaining configuration
So when should I use owned entities?
If you've got a type that's only ever going to appear as a navigation property of another type (e.g. you're never querying against it itself as the root entity of the query), use owned types in order to save yourself some relationship boilerplate.
If you ever anticipate querying the child entity independent of the parent, don't make it owned - it will need to be defined with its own DbSet<T> in order to be called from the context.
While #Whit Waldo explanation is great with respect to technical ef core, we should also try to understand from Domain Driven Design perspective.
Lets observe the classes mentioned in the question itself
public class Job : Entity
and
public class HiringManagerName : ValueObject
Take a note at Entity and ValueObject. Both of them are DDD concepts.
Identity matters for entities, but does not matter for value objects.
Take a look at this write up from Vladimir Khorikov for a more extensive explanation.
I past the summary bullets here.
Entities have their own intrinsic identity, value objects don’t.
The notion of identity equality refers to entities; the notion of structural equality refers to value objects; the notion of reference equality refers to both.
Entities have a history; value objects have a zero lifespan.
A value object should always belong to one or several entities, it can’t live by its own.
Value objects should be immutable; entities are almost always mutable.
To recognize a value object in your domain model, mentally replace it with an integer.
Value objects shouldn’t have their own tables in the database.
Always prefer value objects over entities in your domain model.
So a value object is owned by an entity. So how do we achieve that using EF Core? Here comes the concept of Owned entities. Now go back and read #Whit Waldo answer.
I am not sure I am approaching wrong way or it is a default behaviour but it is not working the way I am expecting ...
Here are two sample classes ...
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Department Department { get; set; }
}
Second one is Department
public class Department
{
public string Name { get; set; }
public List<Person> People { get; set; }
}
Context Configuration
public MyDbContext() : base("DefaultConnection")
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<Person> People { get; set; }
public DbSet<Department> Departments { get; set; }
I am try to load people where last name is from 'Smith'
var foundPeople
= context
.people
.Where(p => p.LastName == "Smith");
Above query load foundPeople with just FirstName and LastName no Department object. It is a correct behaviour as my LazyLoading is off. And that was expected as well.
Now in another query with Eager loading Department,
var foundPeople
= context
.people
.Where(p => p.LastName == "Smith")
.Include(p => p.Department);
Above query loads foundPeople with FirstName, LastName, Department with Department->Name as well as Deparment->People (all people in that department, which I dont want, I just want to load first level of the Included property.
I dont know is this an intended behaviour or I have made some mistake.
Is there any way to just load first level of Included property rather then complete graph or all levels of included property.
Using Include() to achieve eager loading only works if lazy loading is enabled on your objects--that is, your navigation properties must be declared as virtual, so that the EF proxies can override them with the lazy-loading behavior. Otherwise, they will eagerly load automatically and the Include() will have no effect.
Once you declare Person.Department and Department.People as virtual properties, your code should work as expected.
Very sorry, my original answer was wholly incorrect in the main. I didn't read your question closely enough and was incorrect in fact on the eager behavior. Not sure what I was thinking (or who upvoted?). Real answer below the fold:
Using the example model you posted (with necessary modifications: keys for the entities and removed "this" from context constructor) I was unable to exactly reproduce your issue. But I don't think it's doing what you think it's doing.
When you eagerly load the Department (or explicitly load, using context.Entry(...).Reference(...).Load()) inspect your results more closely: there are elements in the Department.People collections, but not all the Persons, only the Persons that were loaded in the query itself. I think you'll find, on your last snippet, that !foundPeople.SelectMany(p => p.Department.People).Any(p => p.LastName != "Smith") == true. That is, none of them are not "Smith".
I don't think there's any way around this. Entity Framework isn't explicitly or eagerly loading People collections (you could Include(p => p.Department.People) for that). It's just linking the ones that were loaded to their related object, because of the circular relationship in the model. Further, if there are multiple queries on the same context that load other Persons, they will also be linked into the object graph.
(An aside: in this simplified case, the proxy-creation and lazy-loading configurations are superfluous--neither are enabled on the entities by virtue of the fact that neither have lazy or proxy-able (virtual) properties--the one thing I did get right the first time around.)
By desing, DbContext does what it's called "relationship fix-up". As your model has information on which are the relations between your entities, whenever an entity is attached, or modified, in the context, EF will try to "fix-up" the relations between entities.
For example, if you load in the context an entity with a FK that indicates that it's a children of another entity already attached to the context, it will be added to the children collection of the existing entity. If you make any chages (change FK, delete entity, etc.) the relationships will be automatically fixed up. That's what the other answer explains: even if you load the related entities separatedly, with a different query, they'll be attached to the children collection they belong to.
This functionality cannot be disabled. See other questions related to this:
AsNoTracking and Relationship Fix-Up
Is it possible to enable relationship fixup when change tracking is disabled but proxies are generated
How to get rid of the related entities
I don't know what you need to do, but with the current version of EF you have to detach the entity from the context and manually remove the related entities.
Another option is to map using AutoMapper or ValueInjecter, to get rid of the relationship fix-up.
You could try using a LINQ query so you can select only the fields that you need. I hope that helps.
I'm banging my head on the keyboard with this one, basically what I'm trying to do is rather simple.
I reversed engineered an existing database with the EF Power Tools, I did that mostly because the database in question is quite old and missing a lot of foreign keys, or even primary key for that matter. The goal was to be able to add navigation properties to the generated model, mostly to have a cleaner code when querying the model.
Now I have 2 classes User and CostCentre, mapped to their respective tables Users and CostCentres with proper primary keys, PK of Users is Username named Userid in CostCentres, theoretical relation between those two is 1 to M (one User can have multiple CostCentre).
I added a navigation property to User like so
public virtual ICollection<CostCentre> CostCentres { get; set; }
I'm initializing the list in the default constructor with a simple
public User()
{
CostCentres = new List<CostCentre>();
}
To CostCentre I added a User property like so
public virtual User User { get; set; }
In the generated CostCentreMap class, I mapped the navigation property like so
this.HasRequired(cc => cc.User)
.WithMany(u => u.CostCentres)
.HasForeignKey(cc => cc.Userid);
Now whenever I query db.Users I can't get the property to fill, I know the navigation property kind of work, because when I do
db.Users
.Include(u => u.CostCentres);
The resulting query does the join properly on the proper columns in each table, however if I do
User user = db.Users
.Include("CostCentres")
.SingleOrDefault(u => u.Username == userName);
The property CostCentres stays empty.
I'm pretty sure I'm missing something quite obvious but for the love of Barnaby Jones, I can't get my hands on what.
Any help would be greatly appreciated.
Starting out on an Entity Framework project.
Imported the Db I am going to use and right away noticed that many table fields were made into EntityKey types and the source fields are not even Keys. Doesn't seem to be a pattern as to which fields were made EntityKeys and which were not.
Is this normal? There were no options for this in the wizard. I don;t want to have to go through and remove this property for all the fields where it was added.
Thanks for your advice!
Each entity on your model requires a unique key, so EF can track and retrieve/persist these entities based on their unique identifier.
If your tables in your database don't have primary keys, then your database is not relational and therefore should not be used by an ORM like EF which is predominantly designed for RDBMS.
If you had an entity like this:
public class Orders
{
public string Name { get; set; }
public double Price { get; set; }
}
How would you retrieve a single order? How would you save a single order?
Crucial LINQ methods such as SingleOrDefault() would be useless, as there is no guarantee that this won't throw an exception:
var singleOrder = ctx.Orders.SingleOrDefault(x => x.Name == "Foo");
Whilst if you had an EntityKey and PK called "OrderId", this is guaranteed to not throw an exception:
var singleOrder = ctx.Orders.SingleOrDefault(x => x.OrderId == 1);
http://msdn.microsoft.com/en-us/library/dd283139.aspx
I think as soon as you read the first paragraph you will understand the role of entity keys in Entity Framework.