0

I have been asked to write a web site that will use an existing SQL Server database. The database was designed to work with another application, and so I can't make any potentially breaking changes to it.

Unfortunately, the database does not contain a single relational link, each table is standalone.

I know you can use EF commands to scaffold a database and create entity classes, but I would like the code to know the relationships that should exist between the tables.

I thought about scaffolding the database, then modifying the created classes to include the links, but I'm not sure if that would allow EF to load related entities. Also, as I will need to add some new tables to the database, I'm worried that EF will try and create those links when I do the migration.

Is there any way to do this?

Avrohom Yisroel
  • 8,555
  • 8
  • 50
  • 106
  • Have a look at this... https://stackoverflow.com/questions/3996782/entity-framework-table-without-primary-key. Basically its a pain in the backside to get it to work. You'll probably want to look at writing your own ORM code, or use something like Dapper. If it was possible to update your schema then that would be the best idea. You can often usually amend the schema of an existing database but remember to backup and test on a mock database before you make any changes to a production DB – Glynn Hurrell May 04 '20 at 20:00
  • @GlynnHurrell I think the OP is saying there are no FKs, not that there are no PKs – juharr May 04 '20 at 20:03
  • Ah ok fair enough – Glynn Hurrell May 04 '20 at 20:04
  • There's not much point in modeling relationships that do not exist in the DB as that's where you'd get the real benefits. – juharr May 04 '20 at 20:05
  • It'll work. You're free to configure any relationship you want from "foreign keys" to primary keys or alternate keys. – Gert Arnold May 04 '20 at 20:09
  • Use ADO.Net instead of EF, and write your own Data Access Layer – Srinika Pinnaduwage May 04 '20 at 20:16
  • Thanks to everyone for the replies. Given that we are only reading the existing tables, not writing to them, I think the easiest way would be to add our own tables that only include the columns we need (as opposed to the three zillion we don't) and add triggers to their tables to keep ours up to date. I think it will be easier in the long run than trying to hack around. – Avrohom Yisroel May 06 '20 at 16:18

0 Answers0