Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

ForeignKey - Migration #4927


User avatar
0
sunilkosuri created

Hello,

I am using ASPNETZERO EF Core + Angular template.

I am using annotations in entities for foreign keys, but the migration is not adding any foreign key constraints. For example,

[Table("Personnels")] public class Personnel : FullAuditedEntity { [Column("Personnel_Id")] public override int Id { get; set; }

	public virtual int? Personnel_Type_Id { get; set; }
	
	public virtual string Last_Name { get; set; }
	
	public virtual string First_Name { get; set; }
	
	public virtual string Middle_Initial { get; set; }
	
	public virtual string Title { get; set; }
	
	public virtual DateTime? Birth_Date { get; set; }
	
	public virtual string City_Of_Birth { get; set; }

            [ForeignKey("Citizenship_Code")]
            public virtual int Citizenship_Code_Id { get; set; }		
}

How can I successfully add foreign key constraints to the migration (and hence the database)?

Also, is it sufficient to add the annotation only to the entity or is it necessary to add it to every place where there is a reference to this Citizenship_Code_Id in Input/Output and DTOs?

Thanks, Sunil


2 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    To configure using Data Annotations, you need a navigation property:

    public class Personnel : FullAuditedEntity 
    {
        // ...
    
        [ForeignKey("Citizenship_Code")]
        public virtual int Citizenship_Code_Id { get; set; }
        public virtual CitizenshipCode Citizenship_Code { get; set; } // Add this
    }
    

    If you don't want a navigation property, then configure using Fluent API.

  • User Avatar
    0
    sunilkosuri created

    Great! Thank you. That works.