简体   繁体   中英

Entity Framework code first - How to define a custom navigation property

I'm using ASP.NET core and Entity Framework

I have a pre-existing database schema, and I want to add a linked table using a foreign key, however the foreign key index column isn't something that adheres to any of the standard EF conventions. How can I express this in Ef? I'd prefer to use Data Annotation attributes if possible, but perfectly fine to use the ModelBuilder fluent API if not.

Essentially this:

[Table("widgets")]
class Widget {
  [Key, Column("id")]
  int Id { get; set; }

  [Column("referencenumber")]
  int ReferenceNumber { get; set; }

  public WidgetReferenceData ReferenceData // ???? How do I express this?
}

[Table("widgetreferences")]
class WidgetReference {
  [Key, Column("referencenumber")]
  int ReferenceNumber { get; set; }

  [Column("value")]      
  string Value { get;set; }
}

In the above model, A Widget may have zero or one associated entry in the WidgetReference table, linked using the widgets.referencenumber database column.

What I'd like to do is add a property to my Widget model to go and load this associated WidgetReference (or null if there's not one present). Basically I want to be able to use it like this:

var referenceValue = FindWidget().ReferenceData?.Value;

If it were a conventional "Id" column, EF would take care of it, but as I have custom database column and property names, how do I express this relation?

I'm not sure it affects the outcome, but it's critical that widgetreferences.referencenumber is NOT a foreign key, but rather just a column with an index on it. Our business logic is such that if a Widget gets deleted, we still want to retain the reference data

I've tried and failed to find the answer to this via Googling, but it feels like something that shouldn't be hard :-(

    [Table("widgets")]
    class Widget 
   {
      [Key, Column("id")]
      int Id { get; set; }

      [Column("referencenumber")]
      int? ReferenceNumber { get; set; }

      [ForeignKey("ReferenceNumber")]
      public virtual WidgetReferenceData ReferenceData // ???? How do I express this?
    }

    [Table("widgetreferences")]
    class WidgetReference 
    {
      [Key, Column("referencenumber")]
      int ReferenceNumber { get; set; }

      [Column("value")]      
      string Value { get;set; }
    }

Just use the ForeignKeyAttribute to associate the Navigation Property with the Foreign Key Property. EF doesn't care if there is actually a Foreign Key in the back-end.

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