'Different entities having an optional foreign key to the same table
I have two tables that have a foreign key to another table, but both could be optional. I'm trying to do it through attributes.
Here are the two entities
public class Subscription : BaseModel
{
public virtual User User { get; set; }
public Guid UserId { get; set; }
public DateTime ValidFrom { get; set; }
public DateTime ValidUntil { get; set; }
[ForeignKey("Regarding")]
public virtual ICollection<RoleAssociation> Roles { get; set; } = new List<RoleAssociation>();
}
public class User : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
[ForeignKey("Regarding")]
public virtual ICollection<RoleAssociation> Roles { get; set; } = new List<RoleAssociation>();
}
And the table for RoleAssociation
public class RoleAssociation : BaseModel
{
public Guid Regarding { get; set; }
public virtual Application Application { get; set; }
public Guid ApplicationId { get; set; }
public virtual Functionality Functionality { get; set; }
public Guid FunctionalityId { get; set; }
public virtual Role Role { get; set; }
public Guid RoleId { get; set; }
}
This works and creates the correct database schema, but when I'm trying to add a RoleAssociation and providing a Guid from a User for example, I'm being returned the following
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_RoleAssociation_Subscription_Regarding". The conflict occurred in database
"SecurityGateway", table "dbo.Subscription", column 'Id'.
It expects that I ALSO add a RoleAssociation for a Subscription which is not what I want.
I have thought of making Regarding optional, but I don't want any rows in that table to not have a value for this column, this would make no sense.
Any ideas ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
