Reputation: 24913
I try to use DDD to describe domain model and code first approach on mapping to database tables with entity framework (using fluent api). For example I have 2 entities: Clubs and Users. Club has many Users. And I need to add new User to Club.
class User
{
public string Name { get; set; }
public Club Club { get; set; }
}
class Club
{
public string ClubName { get; set; }
public ICollection<User> Members { get; set; }
public void AddNewMember(User user)
{
//..some logic and checks
Members.Add(user);
}
}
Upvotes: 0
Views: 570
Reputation: 2473
How about introducting a new domain concept 'Member'. Member could be an aggregate and have his own dedicated repo. or you simply turn off lazy loading with your original design and add it to its collection. this all depends on your business rules.
public class User
{
public Guid UserId { get; set; }
}
public class Member
{
public Guid ClubId { get; set; }
public Guid UserId { get; set; }
}
public class Club
{
public Guid ClubId { get; set; }
public Member RegisterMember(User user)
{
// Check business rules..
return new Member { UserId = user.Id, ClubId = this.ClubId };
}
}
Upvotes: 1
Reputation: 109137
should I load all users collection in Club to add new and save?
No, you can add a new User
to Club.Members
and EF will save the new user. It's not necessary to load the users first.
What is the best way for modeling entities with big collections
That doesn't depend on the potential size of collections but on how you plan to access them. If there are Club
s with thousands of Users
there's no objection whatsoever if you'd want to query a small subset of users by a query like this:
from c in Clubs
from u in c.Users
where c.Type = "Golf" && u.Membership = "Gold"
select u
I always encourage using navigation properties. An EF entity model is for accessing a database in the first place. DDD concerns are secondary.
Of course you should probably always prevent queries in which all users of a club are loaded, unless you really need them.
Upvotes: 2
Reputation: 157
Well it probably makes sense, based on what I can tell from your scenario, to use the virtual
keyword for your collection and let Entity Framework lazy-load your collection
https://msdn.microsoft.com/en-gb/data/jj574232
Basically let Entity Framework do the work for you
Upvotes: 1