Can I map arbitrary SQL queries to Entity Framework fields? - c#

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.

Related

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

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.

How can I get column properties of DB table in entity framework (database first approach)

I'd like to ask, is there any way to get column properties in c# code via entity framework mechanism (database first approach, EF v5)? For example, I have a table in DB, which has a column of type nvarchar(256) with NOT NULL option. Can I get such information using ObjectContext? Or the only way is make a query direct to DB?
If you have a db already set up, you can add a new edmx to your project (Visual c#>ADO.NET Entity Data Model). Choose EF Designer from database, set your connection string, and generate classes from the db context. Once the edmx is added you can select the edmx and see the model diagram. Select one of the models in the diagram, right click and click 'table mapping'.
To see if a property is nullable, expand myEdmx.edmx, myEdmx.tt and then open the generated class you want.

How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?

Assumptions
Using EF 6.1, MVC 5, VS 2013, C#
I have an existing database model designed in Toad DM for SQL Server and it's very important keep it always updated
Steps and Notes
Using ADO.NET Entity Data Model I chose Code First from Database (new feature in EF 6.1) to generate the models. Note: Model classes and DbContext class generated successfuly but NO .edmx or .tt file was generated.
Next I added a new scaffold item: MVC 5 Controllers with views, using Entity Framework. Note: Success, controllers and views generated
Question
From now on I don't want to use Code First to update my database. Instead I want the models to be updated based on database changes. What to do next? If I don't have an edmx file will I not be able to update my model classes from the database?
The Entity Data Model Wizard's Code First from Database does an excellent job creating your entity classes, as if they were created in the Code First style. What you are asking is if there is any way to keep these classes up-to-date as your database changes, similar to the EDMX style "Update Model From Database". From what I've researched this is not possible using the built-in tooling. However, here is one workaround that I've found useful:
Let's say I have database with a product table and customer table. Originally I created a StoreDBContext class, and selected product as one of my objects. Now I want to add the customer table as a new entity to the existing context. Here's how to do this using the Code First Wizard:
Create a new Entity Data Model, call it StoreDBContextTemp or whatever
Choose the code first from database wizard option
Select customer as an object to add (just customer) & complete the wizard
Open the newly created context file, StoreDBContextTemp.cs, and copy the virtual properties of your newly added entities:
public virtual DbSet<Customer> Customers {get; set;}
Paste these new properties into your Original StoreDBContext.cs dbcontext class.
Delete StoreDBContextTemp.cs, and remove the connection string for StoreDBContextTemp in app.config/web.confg etc.
You can now use Customer on the StoreDBContext class
If you add or remove tables you will need to manually adjust fields, but at least you won't need to hand write dozens of properties each time a new table is added to the model.
One more option is just delete the auto generated classes from the project and once again generate them.
While following this approach only thing we need to make sure that is we should give the same name for the data model(class name which inherits from DbContext ) as the previous one.Data model name is highlighted in below snap
Three things.
There's no .edmx when you use Code First.
If you use Code First Migrations you would have to write first the code and after that migrate the changes to database. This helps you to have much more organized you code with no generated code which is an advantage.
There's a plugin in Visual Studio for doing contrary. Entity Framework PowerTools allows you to select the database and map it to objects.
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
The best solution to me is deleting the model and recreate updated one with the same name, keeping in mind two points:
Personal extension methods implemented for the model;
Possible manual relationships between tables added to the model because of not setted up in the phisical db.
My personal solution:
Move all extension methods to another partial class that won't be overrided;
Insert all added properties of an entity to another partial class;
Keep track of all manual relationships in an help file, so you can add them again being sure not to loose anything;
Delete the old model and recreate one new with the same name and update it with the manual relationships of point 3.

EF4 Custom Entities within the same edmx

I have an edmx file that reflects 100% my DB schema.
Along with this I need to create some custom Entities based on the existent, pretty much like a view that will aggregate fields of several entites into a single one.
The problem is that this isn't quite working. I tried several approaches but it always gave me conflicts with the actual entites already on the edmx.
I need to have those entities that reflect my DB schema, so do I have to create another edmx file to hold my custom entites and avoid colisions?
I also though of:
create a stored procedure but then if
I need to filter the SP result I
eather have to add support for serach
on the SP of get all the rows and
filter with Linq2Objects... won't do
this!
create a View, and this one would
work pretty well but I want to try
to do this making use of the EF4
designer and keep everything in one
place.
Could anyone point me to some examples?
I think what you are describing is a view so this is probably the right way to go.
You can store the view code in the edmx using the DefiningQuery node. You don't need to create the view in the database. However there is no designer support for this feature, you will need to hand edit the edmx. The changes you make should be persisted if you refresh the edmx from the database using the designer.
Details here:
http://msdn.microsoft.com/en-us/library/cc982038.aspx
http://blogs.msdn.com/b/davidebb/archive/2010/10/01/the-easy-way-to-create-an-entity-framework-defining-query.aspx
It would be easier just to create the views in the database, and let the designer find and model them.
This entity will be read-only, but of course you can then assign SPs for UPDATE/INSERT/DELETE if you want to support modifications via this view.
You can't define two entities based on same table except special cases (table splitting, hiearchy mapping). In this case you have to use DefiningQuery as #James suggested or QueryView. The difference is that DefiningQuery is defined in storage model and it is common SQL. QueryView is defined in conceptual model and it is ESQL defined on top of already existing entities. QueryView supports only some features of ESQL (for example it doesn't support aggregate functions). In both cases you have to modify EDMX directly (XML), these features are not supported in designer.
Database view mentioned by #James is also an option if you don't want to use these advanced EF features. You can as well simply expose predefined queries on your object context and map return projection to custom type.
Be aware that neither of these methods will allow you to modify, insert or delete data.

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