What's the point of running an EF migration when you can SQL directly in database? - entity-framework

How to create View (SQL) from Entity Framework in ABP Framework
Not allowed to post comments because of reputation. Just trying to get more information on connecting a database to an Entity Framework, without having to switch to a code-first development style. View selected answer's response (he told the OP to basically do the same thing he was going to do in the DB but with EF, and then added an extra step where EF "...ignores..." the previous instructions...
I want to create tables and design database directly in SQL, and have the csharp library just read/write the table values (kind of like how dapper function where it isnt replacing your database, just working along side of it).
The tutorials don't talk about how to integrate your databases with your project. It either brushes over the subject, ignores it completely, or discusses how to replace it.
I don't want to do any EF migrations (i dont want/need to destroy/create database everytime i decide to run, duplicate, or transfer project). Any and all database back-track (back-up/restore) should be done with and thru SQL (within my work environment).
Just to be clear on exactly what i'm trying to learn:
How does somebody who specializes in database administration (building database schema, managing and monitoring data, and has existing database with data established) connect to project to fetch data (again, specifically referencing Dapper's Query functionality).
I want to integrate and design micro-services, some may share the same database connection or rely on another. But i just simply want to read data in a clean strongly-typed class entity, and maybe deal with insert/update somewhere else if i have to.
I would prefer to use Dapper instead of EF, but ABP is so heavily integrated with EF's design, it's more of a headache to avoid it, than it is to just go along with.

You should be able to map EF under ABP the same way as any other project using DB-first configuration.
The consistent approach I use for EF: (DB-First)
Define entities to match the table/view structure.
Define configuration classes extending EntityTypeConfiguration<TEntity> with the associated ToTable(), HasKey(), and any HasMany/HasRequired/HasOptional for relationships as needed.
In DbContext.OnModelCreating: modelBuilder.Configurations.AddFromAssembly(GetType().Assembly); to load all entity configurations. (assuming DbContext is in the same assembly as the models/configurations Substitute GetType().Assembly to point at the entity assembly.
Turn off Migrations. In DbContext constructor: Database.SetInitializer<MyDbContext>(null);
EF offers a lot more than simply mapping tables to classes. By mapping relationships between entities, EF can help generate optimized queries for retrieving data across those related entities. This can allow you to flatten data structures without returning unnecessary data, replace the need for views, and generally reduce the amount of data coming across the wire from the database to the application server.

Related

Development process for Code First Entity Framework and SQL Server Data Tools Database Projects

I have been using Database First Entity Framework (EDMX) and SQL Server Data Tools Database Projects in combination very successfully - change the schema in the database and 'Update Model from Database' to get them into the EDMX. I see though that Entity Framework 7 will be dropping the EDMX format and I am looking for a new process that will allow me to use Code First in Combination with Database Projects.
Lots of my existing development and deployment processes rely on having a database project that contains the schema. This goes in source control is deployed along with the code and is used to update the production database complete with data migration using pre and post deployment scripts. I would be reluctant to drop it.
I would be keen to split one big EDMX into many smaller models as part of this work. This will mean multiple Code First models referencing the same database.
Assuming that I have an existing database and a database project to go with it - I am thinking that I would start by using the following wizard to create an initial set of entity and context classes - I would do this for each of the models.
Add | New Item... | Visual C# Items | Data | ADO.NET Entity Data Model | Code first from database
My problem is - where do I go from there? How do I handle schema changes? As long as I can get the database schema updated, I can use a schema compare operation to get the changes into the project.
These are the options that I am considering.
Make changes in the database and use the wizard from above to regenerate. I guess that I would need to keep any modifications to the entity and/or context classes in partial classes so that they do not get overwritten. Automating this with a list of tables etc to include would be handy. Powershell or T4 Templates maybe? SqlSharpener (suggested by Keith in comments) looks like it might help here. I would also look at disabling all but the checks for database existence and schema compatibility here, as suggested by Steve Green in the comments.
Make changes in code and use migrations to get these changes applied to the database. From what I understand, not having models map cleanly to database schemas (mine don't) might pose problems. I also see some complaints on the net that migrations do not cover all database object types - this was also my experience when I played around with Code First a while back - unique constraints I think were not covered. Has this improved in Entity Framework 7?
Make changes in the database and then use migrations as a kind of comparison between code and the database. See what the differences are and adjust the code to suit. Keep going until there are no differences.
Make changes manually in both code and the database. Obviously, this is not very appealing.
Which of these would be best? Is there anything that I would need to know before trying to implement it? Are there any other, better options?
So the path that we ended up taking was to create some T4 templates that generate both a DbContext and our entities. We provide the entity T4 a list of tables from which to generate entities and have a syntax to indicate that the entity based on one table should inherit from the entity based on another. Custom code goes in partial classes. So our solution looks most like my option 1 from above.
Also, we started out generating fluent configuration in OnModelCreating in the DbContext but have swapped to using attributes on the Entities (where attributes exist - HasPrecision was one that we had to use fluent configuration for). We found that it is more concise and easier to locate the configuration for a property when it is right there decorating that property.

add changes via EF to DB possible?

i've got a question about the tables and stored procedures which are created by aspnet_regsql.exe.
scenario:
new empty database: foodb
execute the script aspnet_regsql.exe for this Database.
now:
can i add a entity model framework for this Database, and add aditional Entities and associations to the existing Entities (e.g. ASPNET_Users) ?
best regards
So, yes you can bring in any database objects to an entity framework model. I'm not sue why you would want to, because these things aren't really made to be directly accessed (there are API's to get to this data).
To your second question of adding new associations, that part I don't think you can do. As far as memory serves, the EF designer does not allow you to just wire up non-existant association. So you would need to actually make the associations within SQL server, and then import them into the model.
I wouldn't recommend doing this if you are still using any of the API's as it might have unintended consequences.

Defining business objects in Entity Framework

Trying to understand Entity Framework. My approach is database first. However I would like to define other entites in the model that is closer to my business objects. I guess I could write queries in the db and include them in the model. But I would also like to define entirely new entities in the model though they would be based on underlying tables in the db. How do I do that - does anyone know a tutorial?
Regards
Bjørn
db Oldtimer, EF Newbie
Database first means that you have existing database and you can either create model by updating from database or manually. You can use wizard to create initial model and modify it manually to define new entities but you must not use update from database any more or some of your changes will be deleted. Also your custom modifications must follow EF mapping rules (for example it is not directly possible to map multiple entities to the same table except some more advanced mapping scenarios like splitting and inheritance) and some of them (custom queries) must be done directly in EDMX source (XML) because designer doesn't support them - this requires more complex knowledge of EF mapping and it will be definitely hard for newbie.
You can check specification of that XML. For entities mapped to custom queries you will have to use DefiningQuery element in SSDL part of EDMX.

EntityFramework withour EDMX

We are about to start using EF as our ORM. We have our own MetaData representing the databse stracture and we will generate whatever we need off of that.
We are wondering whether to use the "old" EDMX approace, or to use the new EDMX free approach (wiht DbSet and DbContext). As we do our own code/edmx generation it seems odd to generate an EDMX and then generate objects and context off of it.
The thing is I don't see much talk about about the EDMX free approach. Is it being used by anyone? Can someone with experience share their impressions? Are there known limitations? Are there pros and cons?
Asher
Are you asking if anybody is using code-first? :) By checking the number of questions in entity-framework-4.1 and code-first and ef-code-first I guess people are using it a lot. There were several questions about code-first x non code-first. Some of I answered:
EF POCO code only VS EF POCO with Entity Data Model
EF Model First or Code First Approach?
EF 4.1 Code-first vs Model/Database-first
Generally there are four approaches:
Model first (database generated from EDMX)
Database first (EDMX generated from database)
Code first (database generated from code mapping)
Database first with code mapping (code mapping manually created for existing database or manually updated mapping generated by EF Power Tools CTP)
Selection of the approach usually depends on the way how you want to develop application (as described in linked answers). It also depends if you want to use ObjectContext API or DbContext API. The former one is usually used with first two approaches (but the secret is it should work with code-first as well) the later one with all of them.
Code first has some limitations - it doesn't support all mapping features EDMX does for example:
Stored procedures mapping (it doesn't mean you cannot execute SP when using code first)
SQL functions mapping
Advanced EDMX features like defining queries, query views, model defined functions
etc.
What I don't understand is why are you trying to combine your code generation tool with EF. Either use your stuff or use EF's stuff. You will avoid complications and incompatibilities.

Entity framework 4 and multiple database

Something changes or it still not support this?
For example join database1.dbo.Users and database2.dbo.Addresses
I actually did find a way to make an EF model span multiple databases if your database supports Synonyms. Basically you setup Synonyms to Database2 on Database1, create separate edmx models for each, then merge the XML
I posted the exact steps to make an edmx file span multiple databases here if you're interested, along with a script to do the merge for you whenever something changes.
I think what ais asked is if you can join tables from different databases, not different providers, resulting in one entity mapped to two or more tables or views from different databases.
If you think about it, when you create a EDM model with Visual Studio it ask you to give an existing database, and when finished creating the model, it generates an EF connection string, that internally address to the given underlying database connection string.
E.g: metadata=res:///EFTestModel.csdl|res:///EFTestModel.ssdl|res:///EFTestModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\;Initial Catalog=EFTest;Integrated Security=True;MultipleActiveResultSets=True"*
So each model matches only a database, only a connection string.
EF4 still does not support creating one conceptual model which works with N storage models. At least this is not supported with any built-in provider. Perhaps in the future this could be done through a new provider that combines the support of many storages (from the same providers or different).
I havent done enough research on it, but perhaps Windows Server AppFabric (Codename Velocity) could be the bridge to go through this gap.
Note: I have tried even editing manually the xml for the EDM (edmx) to insert a second element inside the <edmx:StorageModels> tag but it does not match the EDM XML Schema so VS warns about it:
Error 10021: Duplicated Schema element encountered.
Rafa Ortega
MAP2010
See answer to similar question:
Entity Framework - Inserting entity with multiple models and databases