Search code examples
c#sql-serverentity-frameworkaspnetboilerplate

SQL Server foreign key window issue for newly created EF Code first table


I don't know if anyone face this issue or it's just something else.

I am using a EF code-first architecture.

Here is my first class :

public class PerformanceSurchargeGeneralSettings : FullAuditedEntity
{
    public int PerformanceID { get; set; }
    public Performance Performance { get; set; }

    public int SurchargeId { get; set; }
    public Surcharges Surcharge { get; set; }
}

And here is the second class:

public class Surcharges : FullAuditedEntity
{
    public  string Name { get; set; }

    public ICollection<PerformanceSurchargeGeneralSettings> PerformanceSurchargeGeneralSettings{ get; set; }
}

Everything works fine, I can add migration, update my database but if I go to table and check for foreign key reference, I can't see primary key table. See this screenshot here:

enter image description here

I am not able to find newly added table that is Surcharge in the dropdown of primary key table.

And if I execute SP_help for this table, I can find all foreign keys, see the screenshot:

enter image description here

I don't understand where exactly the issue is ...


Solution

  • H,

    Change your classes as below;

    [Table("PerformanceSurchargeGeneralSettings")]
    public class PerformanceSurchargeGeneralSetting : FullAuditedEntity
    {
        [ForeignKey("PerformanceId")]
        public virtual Performance Performance { get; set; }
        public int PerformanceId { get; set; }
    
        [ForeignKey("SurchargeId")]
        public virtual Surcharge Surcharge { get; set; }
        public int SurchargeId { get; set; }    
    }
    

    [Table("Surcharges")]
    public class Surcharge : FullAuditedEntity
    {
        [MaxLength(128)]
        public string Name { get; set; }
    
        public virtual ICollection<PerformanceSurchargeGeneralSetting> PerformanceSurchargeGeneralSettings{ get; set; }
    }
    

    My advises

    • Use singular names for classes. Surcharges => Surcharge.
    • Give MaxLength to string properties.
    • Use the same case for all Id fields. PerformanceID => PerformanceId. (like you did for SurchageId).
    • Add virtual key when you want to load data with lazy loading.