Although this post is for Entity Framework
not Entity Framework Core
, It might be useful for someone who wants to achieve the same thing using Entity Framework Core (I am using V1.1.2).
I don't need navigation properties (although they're nice) because I am practicing DDD and I want Parent
and Child
to be two separate aggregate roots. I want them to be able to talk to each other via foreign key not through infrastructure-specific Entity Framework
navigation properties.
All you have to do is to configure the relationship on one side using HasOne
and WithMany
without specifying the navigation properties (they're not there after all).
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
protected override void OnModelCreating(ModelBuilder builder)
{
......
builder.Entity<Parent>(b => {
b.HasKey(p => p.Id);
b.ToTable("Parent");
});
builder.Entity<Child>(b => {
b.HasKey(c => c.Id);
b.Property(c => c.ParentId).IsRequired();
// Without referencing navigation properties (they're not there anyway)
b.HasOne<Parent>() // <---
.WithMany() // <---
.HasForeignKey(c => c.ParentId);
// Just for comparison, with navigation properties defined,
// (let's say you call it Parent in the Child class and Children
// collection in Parent class), you might have to configure them
// like:
// b.HasOne(c => c.Parent)
// .WithMany(p => p.Children)
// .HasForeignKey(c => c.ParentId);
b.ToTable("Child");
});
......
}
}
I am giving out examples on how to configure entity properties as well, but the most important one here is HasOne<>
, WithMany()
and HasForeignKey()
.
Hope it helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…