简体   繁体   中英

Navigational property using base class in EF Core

I have a scenario where I have to use a base class for my entities where that base class refers to a property which is a foreign key to an entity I want to do the following:

Billing Account --<- All Billable Entities

public class BillingAccount:Entity
{
    public int AccountId { get; set; }
    public string AccountNumber { get; set; }
    public int OwnerId { get; set; }
    public decimal CurrentAccountBalance { get; set; }
    public virtual Owner Owner { get; set; }
}

Here is the base Entity for all billable items

public abstract class BillableEntity : Entity
{
    public string BillingStatus { get; set; }
    public string ReferencedInvoice { get; set; }
    public bool RecordLocked { get; set; }
    public int AccountId { get; set; }
    public virtual BillingAccount Account { get; set; }
}

For my entities I am planning to extend or implement a base configuration for all billable entity

public class BillableBaseConfiguration<T> : IEntityTypeConfiguration<T> where T : BillableEntity
{
    public virtual void Configure(EntityTypeBuilder<T> builder)
    {
        builder.HasOne(a => a.Account)
            .WithMany()
            .HasForeignKey(a => a.AccountId);
    }
}

But I cannot figure it out how to implement from the base entity. Is there a way or a workaround? Another way that i can think of is to create an SQL view, file up all the billable entity on that and then create a navigational property on the AccountId.

You have multiple options to define relationship one use Data Annotation and Add [ForeignKey("AccountId")] if you use this approach then you do not need to use fluent api to define relations. eg

public int AccountId { get; set; }
[ForeignKey("AccountId")]
public virtual BillingAccount Account { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM