Reputation: 82301
I have these views in my Sql Server database:
Shipment.Shipment
* ShipmentId --> PK
* CourierId
Ref.Courier
* CourierId --> PK
Since these are views, there are no foreign keys on them. The underlying tables are legacy and also do not have foreign keys.
But I want to have my entity framework model think that there are foreign keys. (Specifically Shipment.Shipment.CourierId => Ref.Courier.CourierId
)
I could do this in database first, but I recently switched to "code first" and I can't seem to get it to work using the ForeignKey
attribute.
However, I don't really do "Code First". I retrofitted my entity classes from the views in the existing database.
So, using the "code first" syntax, how can I add an association/foreign key to my existing entities? (even though there is not one in the database)
Here is a paired down version of my existing entities:
[Table("Shipment.Shipment")]
public partial class Shipment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ShipmentId { get; set; }
public int CourierId { get; set; }
[StringLength(50)]
public string Airbill { get; set; }
}
[Table("Ref.Courier")]
public partial class Courier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourierId { get; set; }
[StringLength(50)]
public string CourierName { get; set; }
}
Upvotes: 0
Views: 69
Reputation: 1628
Change your code to
[Table("Shipment.Shipment")]
public partial class Shipment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ShipmentId { get; set; }
public int CourierId { get; set; }
/* this will tell EF about relationship with Courier,assuming it is 1-1 */
public virtual Courier Courier { get; set; }
[StringLength(50)]
public string Airbill { get; set; }
}
[Table("Ref.Courier")]
public partial class Courier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourierId { get; set; }
[StringLength(50)]
public string CourierName { get; set; }
}
Upvotes: 1