LINQ to SQL - Nullable INT in ForeignKey = “Cannot create an association…”
-
08-07-2019 - |
Question
I have a table that has a primary key that's an INT... I have another table, that has a foreignkey relationship to that first table, but it's a NULLABLE INT.
This is perfectly ok, and 100% acceptable to SQL... however LINQ to SQL is complaining about mismatched types ("int to Nullable[int]").
Error Message: Cannot create an association "Store_People". Properties do not have matching types: "PersonID", "ID".
How do I solve this so that the designer stops yelling at a 100% correct usage of SQL?
Solution
Here's what I threw together. Table2's Table1Id column is a nullable foreign key to Table1. I even threw in a few data records and tested some Linq queries...
EDIT: Since I'm getting some downvotes (apparently) for the broken link because this question is 6 years old and the host I used hasn't survived... here's an updated version.
OTHER TIPS
I found the problem. You can create the association ONLY if the parent class doesn't have the Nullable field as the key.
So, this:
will cause this error:
...but this:
will work perfectly.
That looks like a bug (or at least, a stupidity of LINQ to SQL)... but I love it other than that.
I have precisely that situation in a DBML now, and it is working fine.
Primary Key
- Nullable - False
- Primary Key - True
- Server Data type - int NOT NULL IDENTITY
- Type - int (System.Int32)
Foreign Key
- Nullable - Trure
- Primary Key - False
- Server Data type - Int
- Type - int (System.Int32) (actually defined as Nullable in the context.designer.cs file)