We're moving an existing application to .net core 2.1. We currently have a table called ApplicationUser which is referenced by most of the tables in our application because of the audit columns in the tables.
Given the following tables
ApplicationUser
Id Int Identity(1,1)
UserName varchar(100),
...
ProductOrders
OrderId Identity(1,1)
Quantity int
OrderByUserId -->foreign key to application user
LastModifiedByUserId -->foreign key to application user
LastModifiedDate datetime
...
And give the following Entities
public class ApplicationUser
{
public int Id {get;set;}
public string UserName {get;set;}
...
}
public class ProductOrder : IAuditable
{
public OrderId {get;set;}
public Quantity {get;set;}
public OrderByUserId {get;set;}
public LastModifiedByUserId{get;set;}
...
}
public interface IAuditable{
public int LastModifiedByUserId {get; }
public DateTime LastModifiedDate {get; }
}
And this is my DbContext
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<ApplicationUser> Affiliates { get; set; }
public DbSet<ProductOrder> FinancialClientPortals { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MySchema");
modelBuilder.Entity<ApplicationUser>()
.ToTable("ApplicationUser")
.HasKey(c => new { c.Id });
modelBuilder.Entity<ProductOrder>()
.ToTable("ProductOrder")
.HasKey(c => new { c.Id });
// how to set the foreign key on LastModifiedByUserId??
}
}
Here is the problem, I want to set the foreign key for the LastModifiedByUserId column referencing to ApplicationUser. However, the fluent api is forcing me to create the virtual property in the ApplicationUser entity. This is not possible in my case, since all my tables have a foreign key to it.
Is there any way I can set the foreign key in EF Core without having explicitly set the properties on both entities?
Thanks,
Both EntityTypeBuilder.HasOne
overloads have a navigationName
parameter that defaults to null
. The docs state that "If no property is specified, the relationship will be configured without a navigation property on this end."
The ReferenceNavigationBuilder.WithMany(String)
method's collection
parameter also defaults to null
. The docs state that "If null or not specified, there is no navigation property on the other end of the relationship."
Finally, in the ReferenceCollectionBuilder.HasForeignKey(String[])
method, you pass the name(s) of the properties of the foreign key in a string array.
Therefore, in your case, I would create the foreign key as follows:
modelbuilder.Entity<ProductOrder>()
.HasOne(typeof(ApplicationUser))
.WithMany()
.HasForeignKey("LastModifiedByUserId");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With