0

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; }
}
2
  • try adding public virtual Courier Courier { get; set; } in shipment class and public virtual Shipment Shipment { get; set; } in courier class Commented Feb 19, 2016 at 4:47
  • @AnshulNigam That did it! So simple! (Though I just needed to add to the shipment class for my scenario). If you want to post as answer I will accept. (Thanks!) Commented Feb 19, 2016 at 17:01

1 Answer 1

1

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.