Search code examples
asp.net-mvcentity-frameworkef-database-first

Database-first key annotations unrecognized by entity framework


I am trying to use partial classes to decorate EF's auto-generated entity models for SQL views that I have access to. These views are 1:1 representations of tables, but omit the primary keys and foreign key constraints present in the database. I would like to reproduce these keys/constraints with data annotations, but attempting to use them within EF fails.

Any attempts to use Include or Find within LINQ always fail. The foreign key defined here, for example, does not seem to be recognized:

public class FactTimeEntryMetadata
{
    [Key]
    public int TimeEntryKey { get; set; }

    [ForeignKey("DimEmployee.EmployeeKey")]
    public int EmployeeKey { get; set; }
}
[MetadataType(typeof(FactTimeEntryMetadata))]
public partial class FactTimeEntry { }

public class DimEmployeeMetadata
{
    [Key]
    public int EmployeeKey { get; set; }
}
[MetadataType(typeof(DimEmployeeMetadata))]
public partial class DimEmployee { }

In this example, the FactTimeEntry contains TimeEntryKey as a primary, and a column for EmployeeKey, referring to the foreign key in DimEmployee. Is my syntax off in some way, or is this simply not possible with Entity Framework database-first?

Edit:

I have also tried to add a virtual reference to the object, like so:

public class FactTimeEntryMetadata
{
    [Key]
    public int TimeEntryKey { get; set; }

    [ForeignKey("DimEmployee")]
    public int EmployeeKey { get; set; }

    public virtual DimEmployee DimEmployee { get; set; }
}
[MetadataType(typeof(FactTimeEntryMetadata))]
public partial class FactTimeEntry { }

public class DimEmployeeMetadata
{
    [Key]
    public int EmployeeKey { get; set; }
}
[MetadataType(typeof(DimEmployeeMetadata))]
public partial class DimEmployee { }

but was also unsuccessful this way.


Solution

  • Your only three options using :

    1. Put your keys and relationships in your database. Relational Databases were created to be relational. If you don't do that, why use a database?

    2. As Gert Arnold metion in his comment, edit the EDMX and assign your associations.

    3. Edit the T4 templates with custom code to add Keys/relationships to your objects.