I am using a SQL Server database currently and need to connect it to ASP.Net using Entity Framework. I currently have no foreign keys in my database, will I still be able to scaffold the database and run LINQ queries with commands such as .Include()
?
The current problem I'm encountering is my database model stores historical data so I have several tables with composite primary keys. Without that one to one relation in the database I am unable to run any queries in regards to relationships such as the .Include()
method.
So my questions are as follows:
Do I have to include foreign keys in the SQL Server database in order to use functions such as .Include()
?
I read online that the easiest way to include a FK relation between a primary composite key and a single PK in a SQL Server database would be to create dummy columns in the tables in order to relate the composite primary key to the tables foreign key. Is there a better way to create a FK relationship outside of creating dummy columns or restructuring the data?
Below is a example of how the composite primary key to single primary key looks:
ID*| CODE* | YEAR* | SEQ*| DATA
01 | ABCD | 2015 | 01 | 23
01 | ABCD | 2016 | 01 | 24
02 | ABCD | 2016 | 01 | 21
CODE* | DESC
ABCD | AlphabetSoup
Do I have to include foreign keys in the SQL Server Database
No, you can add associations to your model. But that doesn't mean it's sensible to do without foreign keys in the database. If you can, add them asap, preferably yesterday.
You could add the association to the EF class model by using the fluent API, for example:
modelBuilder.Entity<Main>()
.HasRequired(m => m.Code).WithMany()
.HasForeignKey(m => m.CODE);
... where Main
is the table with the composite PK.
create dummy columns in the tables
Not sure what you mean by that. As you see, one field of the composite PK can perfectly well serve as a FK to one PK field in another table (denoted as Code
).
Again, add foreign keys to your database so you'll have referential integrity. Currently, there's no guarantee that Include
will work properly, because there can be unmatched values in the Main
table's CODE
column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.