Must I use all tables in an Entity Framework model? - entity-framework

I am building an Entity Framework model for a subset of the Pubs database from microsoft. I am only interested and publishers and books, not publishers and employees, but there is a foreign key constraint between the publishers and emoloyees tables. When I remove the employees entity from my model, the model won't validate because of the foreign key constraint.
How do I create a model for a subset of a database when that subset links to other tabes with foreign key constraints?
Because this is for a demo, I deleted the offending tables and constraints from the database, but this won't work in production.

The correct way to do this is by exposing the foreign key columns as scalar properties. There is a complete explanation, and downloadable sample code, in this blog post. You might find the rest of the post interesting, as well.

You could create views of the pertinent data and bind your model to that. I am not a database expert, but a DBA that I formerly worked with recommended this approach because she said that the view is less intensive on the database server to begin with.
Prior to the release of 3.5 SP1, we built a DAL on top of LINQ to SQL (without DBML mappings, but that is another story) that mapped all of the domain objects to either stored procedures or views. That way, the DBA was happy about the calls following a more set execution plan, as well as being able to encapsulate the database logic outside of the codebase.

Related

What SQL Server 2017 features are not supported in Entity Framework Core code first?

Our team is thinking of utilizing Entity Framework Core code-first to help model the database. We can have both DB projects and EF models, as per article here Database Projects vs. Entity Framework Database Migrations utilizing schema compares, just trying to figure out what will be the source of truth?
Does Entity Framework support all features in SQL Server SSDT Database Projects?
What features does EF Core 2 not support? (eg, does it not support any of following: triggers, views, functions, stored procedures, encryption keys, certificates, db properties (ansi null, quoted identifier), partitions)
I am trying to locate the Microsoft Resource.
tl;dr Database Projects are feature-rich, but database-first. Migrations is code-first, but has a very limited built-in set of database features.
For many people it won't be relevant to compare Database Projects and Migrations. They represent two different modes of working with Entity Framework. Migrations is code-first, DP is database-first. Sure, you can use migrations to control the database schema and besides that keep a DP in sync with the generated database to satisfy DBAs (as the link suggests). But both lead their own separate lives and there's no Single Source Of Truth.
So comparing them is useful if you're not sure yet wich working mode you're going to choose.
For me the most important difference is that DP will cover all database objects and detect all changes between them when comparing databases. Migrations only detect changes between a database and the mapped model. And the set of options for generating database objects is very limited. For everything you need additionally you have to inject SQL statements into the migration code. These statements are your own responsibility. You have to figure out yourself if a migration needs an ALTER PROCEDURE statement or not (for example). EF won't complain if the script and the database differ in this respect.
This is the main reason why I've never been a great fan of migrations. It's virtually impossible to maintain a mature database schema including storage, file groups, privileges, collations, and what have you.
Another advantage of DP is that they're great in combination with source control. Each database object has its own file and it's very easy to check the change history of each individual object. That's not possible with generated migrations. Indeed, many intermediate changes may never make it to a generated migration.
Of course the obvious advantage of migrations is the possibility to do a runtime check (albeit incomplete) whether the code and the database match. In database-first projects you need to create your own mechanism for that.
EF Core is only ORM.
1) You should be ready to create all DB objects except tables manually. What I create manually: constrates (defaults as well as conditions). Since this is code first - there is no need in SP, functions and so on. If you use ORM - DB is only storage. Of course practice is important. For me default constraints adds comfort on tables where I create test data manually. And conditions also are usefull in situations when you do not trust your (team) code.
2) you will do creation (and dropping) of views, triggers, sp and so on to the "migration" code (there is such concept in EF) in plain sql:
migrationBuilder.Sql("CREATE VIEW ...");
As a result you could have a separate "migration" program (e.g. command line tool) that install or remove both Ef Core tables and your manually created objects, do and revert the data migrations.
"EF Core migrations" is quite complex api (reserve a week for learning). Interesting topics: managing several dbcontexts in one db, createing db object during migration from model annotations, unistall. Or find a freelancer for it (this part of project is good for outsourcing).

Hiding a bad database schema behind neater domain POCOs

I'm working on an application that interfaces with a slightly odd database. The design of this database is pretty bad; there are basically no foreign keys (although there are columns that reference other tables, they're not set as keys), columns are named very ambiguously, and the structure does not lend itself to the kind of logic I'm aiming to do (mostly, it forces joins for operations that should be simple, and leaves you trawling through needlessly massive tables for things that could have been split).
Unfortunately, I'm stuck with this database. It's being replicated off a third-party system, so I can't change the table structure or anything. I can add stored procedures and views, though.
In the application, I've come up with a set of classes that I can work with much more easily. I've got quite a bit of experience with Entity Framework, so I'm planning to use that. My initial hunch is that I can add views to the database that return things in the format of my classes, and then from there on out just pretend that they're tables. I've never tried anything like this before, though, and I'm not entirely sure how to proceed.
How can I use Entity Framework to map my classes to these views? Note that it kinda needs to be my POCO classes, rather than anything EF auto-generates - is there a way to tell EF to map existing classes?
If you use code first then Entity Framework will generate CreateTable instructions in the migrations. To use a view instead, replace this code with your own Sql to generate the View. See the answer to this question: Mapping Database Views to EF 5.0 Code First w/Migrations
I would also configure Entity Framework to use stored procedures. Then you can tailor the insert/update/delete sql to match the underlying tables. Again, you can do this by altering the sql that is generated for you in the migrations.

What advantages my BO deves gets in case of using EF with SQL Server having all relationships maintained?

I am a DBA. I want to know what advantages my Business Objects developers will get when using EF with SQL Server DB which is fully managed using Foreign keys and Primarkey as and when require. As this is our new project and we have to use EF with SQL Server 2008 R2. We have a plan to use Database First Approach. Can anyone tell me what difference my Business Object developer will experience in case If I define all foreign Key relationships in my DB?
Assuming it's setup correctly, when your developers actually create their objects from the database structure, they'll be able to access any related tables rather easily.
It should also make creation of new objects (rows in the tables) easy, as it then shouldn't be possible to create new items that would break the foreign key relationship.
It's also just plain good practice to correctly setup any foreign keys in the database; I'm not sure of any benefit not to.
As a developer that's had to work with data sources that haven't been setup correctly, I can tell you a correctly setup database structure is an amazing experience for a developer.
(As an aside, as a DBA, you may want to take a look at EF. Also take a look at LINQ, one of the items that they'll be using. In particular, Why LINQ beats SQL may help you get a basic understanding, even if you don't agree with the article title :) )

Foreign Key mapping in Core Data

I understand that Core Data is not a relational database but I need to understand how it can be used to support a client/server model where the server uses a Rails, ActiveRecord, Mysql setup.
My app is pulling records from the server using JSON and I am mapping the relationships using Core Data.
The Foreign Key in the SQLLite database is showing the PK field of the related table even though I have set the User Info Key/Value of primaryAttributeKey => id. (I can't remember where I saw this mentioned.)
Is there any way to setup the models so they will use my id as the PK so that it will clean up the export of related data back to the server?
Edward,
The PK is just a field in your object. If you want to maintain them in CD, they are just numbers. As you build your object graph, you have to maintain them in parallel with your relations. Of course, exporting records created on the device back to your server will have difficulty -- FKs and PKs are unique to each table and that uniqueness is determined on the server. Hence, tracking these numbers is not that useful.
May I suggest that your JSON needs to be structured such that it is redundant -- that it has both the data and the various PKs and FKs, if any?
Finally, you appear to be making a CRUD focused API. Generally, those are low performance APIs for remote devices. There are other problems with CRUD APIs, such as inconsistent business logic between servers and clients. I would suggest you to rethink your APIs.
Andrew

Accessing runtime-created tables with Entity Framework

We have an application that creates new tables at runtime, but always with the same table schema. The only thing that varies from one of these tables to the next is the table name. Is it possible to access these tables using Entity Framework, specifying which table to access by name?
Entity Framework is not designed for DDL, it's an ORM tool for data access. You would want to use a simple ADO.NET query to create/drop the table.
Creating and dropping tables for every user session will make your log file grow very big very fast. I would consider carefully the reasons you think this is necessary. If the data is temporary, why not save the Session ID in each row and truncate the table on a daily basis?
UPDATE:
No, not really. The Entity Data Model is not dynamic, it's a static XML document that describes the structure of the database. If you want to interact with a table with a dynamic name, you're going to have to stick to "classic" ADO.NET.
With Linq to SQL I guess it would be possible with a stored procedure taking the table Name as a parameter.
A nice post about SP in L2SQL: http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx
I don't know if that feature exists in EF.