Entity Framework 6.0 SQL-first synch with database without .edmx? - c#

I have a database with some tables for school related project and I have a model with EF 6.0 SQL-first approach. I need to update the database with a new table & update an existing table with a new column. The twist is: I don’t have any *.edmx file.
How can I update the model without it? If it is impossible, then how can I generate *.edmx without interrupting the existing model?

Entities are essentially POCOs, so you really just need to update your schema and update the entity classes to match. For new entities if the project is not using an edmx then it should either be using classes extending EntityTypeConfiguration or setting things up with the modelBuilder on the OnModelCreating event in the DbContext.
EF can resolve most general mappings using convention, so adding a column to a table usually just means adding the property to the entity. Mapping only comes into play when you want to change a columns naming, handle type casting differences, or use identity/computed columns. For new entities it can also use convention, but commonly there would be config used for the Table name, PK name, and things like Identity columns, plus navigation properties for related entities.

Related

Add entity relationship to EF Core scaffolded entity when database cannot be changed - and retaining the addition on rescaffold

I am using a database-first approach to a third party database that I cannot change. The database has two tables that should have a constraint defining their primary/foreign key relationship. The constraint is missing so the entities generated do not have the relationship. Is it possible to add the entity relationships to the scaffolded entities without losing my additions if I need to scaffold again (due to an upgrade etc)?
I've thought about creating a custom partial class file extending the existing entity but this will not work if the existing entity already has a constructor. I need a constructor to instantiate a HashSet<T> of the other side of the relationship. I've also thought about using inheritance but not sure if that will work well with the existing entity.
Update: It seems like easiest solution may be to instead use linq join syntax and not provide the relationship in the entities but I'll leave the question up in case anyone has a good solution and a use case where it is beneficial.

Using EntityFramework C# code-first from database - how to map table with no primary key

I am building an Ntier application with EntityFramework c#.
I am adding an Entity Data Model in my Data Access Layer with code-first approach from existing database.
Some of the tables of my db weren't included because they don't have primary key. I have seen some ways to work around this problem, modifying EntityFramework's edmx to force the mapping to the database, disguising some field like a key. But I am not using the .edmx, since I can't use automatic migrations with it. I only generate POCOs from my existing database and then go on with code first migrations.
Is there a way to force Entity Framework to generate a POCO for those tables without primary key ? Some only have one entry and really don't need PrimaryKey
In the end, I just wrote my own POCOs for the tables that weren't included.
I used an attribute [KEY] above the property i wanted to act like key. I added DbSet lines in the DataModel and EF did recognize them in my database.
I didn't want to generate primary keys because my boss didn't want, and thats a reason good enough. :) Hope the best for you thx for answer

Can I map arbitrary SQL queries to Entity Framework fields?

Is it possible to add fields to an entity framework class that rather than being mapped to a column in a table instead map to a SQL query?
For a contrived example (NB: This is not what I'm actually trying to do just an easier to explain example of what I'm trying to accomplish) I want my class to have a TableCount field that holds the result of SELECT COUNT(*) FROM MyTable at the time the object was loaded from the db.
EDIT: I should have mentioned this in my original post but I'm using POCO classes.
You cannot do it directly with entity mapped to a database but there are two ways how to achieve it with a new entity type containing columns from your original entity and your additional computed columns:
Create database view and map that view - this is fully automatic way maintained by EDMX designer for you
Write query to populate whole new entity type and map it manually in DefiningQuery. The disadvantage is that it requires manual EDMX editing and without additional (commercial) tool also manual maintenance of EDMX because standard VS EDMX Designer overwrites edited SSDL part every time you select update from database.

Entity Framework - Inserting entity with multiple models and databases

I have my domain split into multiple Entity Framework models. I have some shared entities that span multiple models (named Lookup), however, these are replaced with "using" references using the methods described in Working With Large Models In Entity Framework. However, what makes my case slightly more unique is that I'm also separating these models into multiple databases (one per model).
I'm having a problem inserting one of my shared entities into my common DB. It's failing with the error:
The member with identity
'Harmony.Members.FK_ResidentialAddress_ResidenceTypeLookup'
does not exist in the metadata
collection.
That foreign key that it's referring to does not exist on the "common DB". But I'm also not working with the entity on the other side of the relationship (named ResidentialAddress); nor do I even have the context that would contain the other entity initialized (named MembersDb). However, both models are compiled into the same assembly.
There are no navigation properties going from Lookup to ResidentialAddress. Though there is a navigation property in the other direction (which I won't be persisting - only using in memory).
My MetadataWorkspace for the EntityConnection of the CommonDb context was explicitly initialized with only the SSDL/CSDL/MSL for the data required for that database. I have confirmed there is no references to the foreign key mentioned in that set of schema data.
var metaAssembly = typeof(CommonDb).Assembly;
var schemaResources = new string[]
{
String.Format("res://{0}/Common.ssdl", metaAssembly.FullName),
String.Format("res://{0}/Common.csdl", metaAssembly.FullName),
String.Format("res://{0}/Common.mdl", metaAssembly.FullName),
}
MetadataWorkspace metadata = new MetadataWorkspace(schemaResources, new []{ metaAssembly });
EntityConnection connection = new EntityConnection(metadata, myDatabaseConnection);
POSSIBLE CLUE: It does work when I go into the generated classes and remove all of the EdmRelationshipAttribute attributes along with their paired EdmRelationshipNavigationPropertyAttribute from the related models (MembersDb).
Key questions:
So why is it that Entity Framework is trying to do something with the relationship that is for an entity that is neither in scope and nor will it be affected by the insertion of the record!?
I am happy to have the generated code remove the attributes mentioned above, but I still want the navigation properties to remain. How would I go about altering the CSDL to achieve that?
NOTE: Persistence of the "child" models is not a priority, nor is the integrity of their now cross-DB foreign keys. These databases are persisted using SQL CE but they were originally generated from a single master SQL Server database.
If each part of your model is written to a separate database, then perhaps the edmx files should not know about each other (about entities or relationship to entities that do not belong to them).
How about trying one of the following approaches:
(To end up with same entities classes for each part, but make EF oblivious of connections between them.)
Remove the "usings" from edmx + cancel auto generation and create classes yourself.
Remove the "usings" from edmx + modify t4 template to read more than one edmx when creating the classes.
Copy edmx files aside so you have two sets of edmxs.
3.a. Use set #1 for auto generation of entities.
3.b. Modify set #2 by removing the "usings" and use for generation of repository classes (objectsets).
Let me know if one of these works.
Good luck,
Danny.

Do I need to include all fields in my entity framework model

Quick question for everyone:
Do I need to include all the database table fields on my EF model?
For example; I've created a sub-model that only deals with tblPayment and associated tables. Now, I need to write a LINQ query to get some information about items. I would typically get this by joining tblPayment to tblInvoice to tblInvoiceItem to finally tblOrderItem.
I'm wondering if when I add in those other tables, do I need to include all the fields for tblInvoice and tblInvoiceItem? Ideally; I'd just like to keep the fields I'd need to join on, as that would limit the possibility of my sub-model breaking if other fields on those tables are modified/deleted.
Can I do this?
No, you don't need to include them all.
However, the GUI mapping tool, when reverse-engineering an existing DB into an EF model, will always include all columns, and there's no way to tell it not to.
Therefore, to exclude columns, you must do one of the following
Manually edit the EDMX yourself. Simply deleting the columns in the GUI designer may work, but only removes the columns from CSDL, not SSDL. The EF may or may not let you do that, depending upon the column's SSDL mapping.
Generate the model from a different DB, which has a similar schema except that it lacks those fields.
Code-first or model-first (EF 4 only).
Yes, you can remove other fields from the entities.
You can not only remove fields from entities, your entities can be combinations of different tables.
Entity Framework

Categories