EF 6 how to set two foreign keys to same table

c# entity-framework

Accepted Answer

The remark made by @T.Glatzer is accurate. Your dependent entities should disclose foreign key properties:

public class UserForms
{
    public int Id { get; set; }

    public string FullNames { get; set; }

    public int IndividualsCountryId { get; set; }
    [ForeignKey("IndividualsCountryId")]
    public virtual Countries IndividualsCountry { get; set; }

    public int BusinessCountryId { get; set; }
    [ForeignKey("BusinessCountryId")]
    public virtual Countries BusinessCountry { get; set; }
}

I employedint Nonetheless, if either of these navigational features is optional, you would just use its replacement.int? or System.Nullable<int> rather (which will result in anint NULL column within the database as opposed to anint NOT NULL ).

Even though EF does not mandate that you expose navigation attributes, doing so is usually a good idea. Believe me. It will aid you in avoiding unpleasant surprises later. In order to aid EF in better understanding how to map relationships, some EF exception messages advise providing foreign key attributes on the entity classes. One such instance is shown here as an example. Keep in mind the "Additional Information" section:

{"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.DependentTable_dbo.PrincipalTable_Id". The conflict occurred in database "DatabaseName", table "dbo.PrincipalTable", column 'Id'. The statement has been terminated."}

Additional information: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

9
2/18/2015 12:11:53 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow