Search code examples
entity-framework.net-coreentity-framework-coredata-annotationsef-model-builder

EF Core: Optional one-to-one foreign key relation from content entity


I've implemented some database context for my .net core blazor application. The database context has access to an external database (no database migration etc.)

Now my problem is that I am not sure how to define a foreign key using fluent api or data attributes when the parent table contains the foreign key for the table.

As simplified example: I've got a transactions entity with data like this:

[Table("transactions")]
public class Transaction
{
  [Key]
  [Column("id")]
  public int Id { get; set; }

  [Column("trans_num")]
  public string TransNum { get; set; }

  [Column("shop_id")]
  public int? ShopId { get; set; }

  [Column("total_amount")]
  public decimal TotalAmount { get; set; }

  public Shop Shop { get; set;}
}

And some shop entity with data like this:

[Table("shops")]
public class Shop
{
  [Key]
  [Column("id")]
  public int Id { get; set; }

  [Column("shop_name")]
  public string ShopName{ get; set; }

  public Transaction Transaction { get; set;}
}

As the models indicate, the "shop_id" is the foreign key.

So ... I've got no transaction reference within my shop entity. Also, in my productive scenario I've got some optional relations like this, meaning for example shop_id would be null.

How would I indicate the optional relation to my model builder?

Best regards


Solution

  • set optional FK in model builder

    [Table("shops")]
    public class Shop
    {
      [Key]
      [Column("id")]
      public int Id { get; set; }
    
      [Column("shop_name")]
      public string ShopName{ get; set; }
    
      public virual ICollection<Transaction> Transactions { get; set;}
    }
    
         modelBuilder.Entity<Shop>()
                .HasMany(c => c.Transactions)
                .WithOptional(c => c.Shop)
                .HasForeignKey(c => c.ShopId)
                .WillCascadeOnDelete(false);
    

    if you are looking only for EF core then you can refer this link :

    WithOptional with Entity Framework Core