I'm using Entity Framework 5, and I reverse engineer code first the database I'm using, and then I added an ADO.NET Entity Data Model so that I can use Stored Procedures as reverse engineer code first didn't provide the use of sprocs. Is this the only way to access sprocs?
Also, I realize that after the reverse engineer code first process is done a bunch of classes (tables from the database) are created but as soon as I add the ADO.NET Entity Data Model, most of the classes go away. Does anybody know why?
DbContext.Database property exposes useful methods
http://msdn.microsoft.com/en-us/library/system.data.entity.database(v=vs.103).aspx
ExecuteSqlCommand( string, object[] )
http://msdn.microsoft.com/en-us/library/system.data.entity.database.executesqlcommand(v=vs.103).aspx
SqlQuery<TEntity>( string, object[] )
http://msdn.microsoft.com/en-us/library/gg696545(v=vs.103).aspx
There is a pattern that you can follow to create or support store procedures with the code first approach. here is a link that you can use to follow this:
http://www.codeproject.com/Articles/179481/Code-First-Stored-Procedures
In few words you need to do the same that you do with model first, create a class that supports the inputs and a class that supports the result set.
And about the Data Entity Model and missing classes. You need to consider that you only can have one approach in a project: code first/(model first/database first), so this could be the reason why you are not seeing those clases.
You can use Context.Database.SqlQuery to run SP.
Related
I am working on ASP.NET Core MVC Application that uses Entity framework Core. So everything seemed ok but somehow i came up with an interesting question and couldn't find the answer in the web.
Here what i know.
When we use EF Core it gives us ability to represent database tables as classes and to work with them. I have a CONTEXT.cs class that creates entities, gives them properties corresponding to database.
Here is my question
If a model is a class then where is the constructor? Or that is done when i "create" something and the whole info comes to controller like this( [Bind("id", "name") ]Materials materials) and data is simply being added to context
Thanks in advance. Please correct me if i'm writing anything wrong
I think that this link will answer the first part of your question:
https://learn.microsoft.com/en-us/ef/core/modeling/constructors
And about binding models which coming from controller actions. At least in previous versions, the data was set through public field setters that can implement complex logic. For example, a boolean setter can actually add a value to a private List when assigning a 'true' value.
My ASP.NET MVC web app needs to get data from existing database using T-SQL stored procedures. I've seen tutorials on how to do that using the code-first approach (basically for a model named Product, the Entity Framework generates stored procedures like Product_Update, Product_Delete, etc).
But in my case I can't use code-first b/c the database and the stored procedures already exist and their names don't follow this convention. What's the way to go? Any help will be appreciated. Thanks in advance.
Begin Edited 2017-03-28
If I go about using straight ADO.NET classes as Shyju and WillHua said, will data annotations on my Model data classes work? If not, how else can validation, etc be implemented?
If I follow this approach, do I need to reference Entity Framework in my project at all?
End Edited 2017-03-28
If you're using Entity Framework you could do something similar to the following:
var startDateParam = new SqlParameter("StartDate", 8) { Value = startDate };
var endDateParam = new SqlParameter("EndDate", 8) { Value = endDate };
var parameters = new[] { startDateParam, endDateParam };
var result= Context.Database.SqlQuery<CampaignReferralReportItem>("CampaignReferralReportItems #StartDate, #EndDate", parameters).ToList<CampaignReferralReportItem>();
return result;
So what you've got here is the declaration of two parameters which are passed into the Stored Procedure 'CampaignReferralReportItems'. After the query is complete, the result is mapped as closely as possible to the class CampaignReferralReportItem.
Keep in mind the order of the properties must be identical as the query results or the mapping can throw exceptions.
It's worth noting that the Context stated in the above code is your DataContext.
Also, before you start throwing this kind of code everywhere. It might be worthwhile looking at the Repository pattern
I'd suggest either using Dapper, which I am strating to use, and love for it's speed - or, Entity Framework, and 'Update model from Database' - so, a database first approach, where the references to the procs are pulled in.
But, I'd suggest Dapper, as it's pretty simple and quick.
I am currently developing project using C# MVC and entity framework, I want to use the entity framework in other modules ,
i.e security module , Utility module ,
i want to call the db using the entity frame work, how do i do this ?
i am new to this are please explain in detail, idea is to break the project into presentation layer, business layer and data access layer..
i don't know how to archive this.
Try this way,
There are three ways to work around entity framework, Database First, Model First & Code First.
Database First: If you already have database, then entity framework can generate a data model that consists of classes & properties that correspond to existing database objects such as tables & columns.
The information of database structure, conceptual data model & mapping between them is store in the xml in an .edmx file.
Model First: If you don't have database, you can start creating model using vs entity framework designer. This approach also use the .edmx file.
Code First: In this approach, we don't need .edmx file. Mapping between store schema & conceptual data model is represented by code, handled by code convention & special mapping API.
Here I have used the Database First approach.
In order to use the Dal class lib, add the reference in the business logic layer and initialize the entities class. For example
Find the entity framework object.
Initialize the entity framework object in other class lib.
FrameworkEntities entities = new FrameworkEntities();
Please let me know, if you want to use model first or code first approach.
Get started from the below link for the Entity Frame Work
http://msdn.microsoft.com/en-US/data/ee712907?
I have an entity/table that uses sqlgeography.
Since EF 4.X doesn't support spatial types I'm instead sending the bytes of the field back and forth.
I have stored procs on the database side that handles the converstion and properties on the code side to do that job.
To add the properties in the code I used a partial class.
One of those properties is for the SqlGeography which simply wraps around the byte[] property to handle getting and setting.
This property is hidden from EF using the NotMappedAttribute.
The other is the property exposing the byte[] itself and is decorated with the EdmScalarPropertyAttribute and DataMemberAttribute.
I then go to the EF model designer (*.edmx) to point the entity model at the Insert/Update/Delete stored procs.
It finds the stored procs alright and realises that they (when appropriate) take a VARBINARY parameter.
It also has a drop down allowing you to select a property on the entity class which maps to that parameter.
However this drop down doesn't list either of my properties. I don't care about the SqlGeography property since that is meant to be hidden from EF, however it is vital for me to be able to point it at the byte[] property, as that is where the data comes from.
I would very much like to avoid database triggers or wrapper classes and addiitonal fields to fudge this in to working.
I tried manually editing the .edmx file to include the byte[] property, but then it just complains it's unmapped.
Can anyone give me some insight in to how to get this to work? Or an alternative method of achiving the end result?
We could use a view to create the binary field for us, but this then involves manually creating a lot of the xml for the relationships within the data.
This pretty much voids the point of using EF which is to make life simple and easy.
For this project We'll just add a binary field to the table then have sprocs to handle the converstion on the server and a property in a partial entity class for exposing the geography type in the model.
Next project I doubt we'll be using EF. Dapper is so much more painless, even if theres a touch more code writing involved.
Here's the links for using views if anyone thinks it would be applicable to them:
http://thedatafarm.com/blog/data-access/yes-you-can-read-and-probably-write-spatial-data-with-entity-framework/
http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/
In the end we created a computed column for each table that exposes the spatial data as bytes.
We then use stored procs for inserting and updating the spatial data.
is there an possibility to call the Math.Sin()-function in a Linq To Entites (Entity Framework 4) -Query?
I've read, that the current Entity Framework 4 doesn't implement this function.
Maybe there's a workaround to this solve problem?
(I don't want to invite all entries in the memory.)
Thanks and best regards
Several functions that (usually) have obvious SQL counterparts, like Math.Sin can't be used directly in Entity Framework queries. Presumably this is because they can't be reliably translated to different SQL implementations. A ton of MSSQL-specific functions are, however, exposed as static methods in the class System.Data.Objects.SqlClient.SqlFunctions. They throw exceptions if you call them directly, but are translated into the proper SQL if used in a LINQ query.
See this blog post about the magic that's happening under the covers (namely the EdmFunction attribute).
It is certainly possible to use such function starting with EF4. In EF4, EF team introduced SqlServer functions that can be consumed in linq. You should alway consider using canonical functions cuz they are database agnostic and every vendor should convert those functions to store specific equivalent. However when such functions are not available, you can resort to SqlServer namespace (ESQL) or SqlFunctions for linq
from l in db.Locations
select SqlServer.Sin(l.Latitude) + SqlServer.power(l.Longitutde)
I cover several of these options in my functions chapter in my book. Specifically you can look at 11-10 recipe Calling database function in esql
11-11 Calling Database Function in LINQ
Unfortunately it's impossible to call Math.Sin in a LinqToEntities query (or Entity SQL query).
The only way to accomplish this without resorting to retrieving all objects first, is to write a SQL query that does what you want and call it via ObjectContext.ExecuteStoreQuery. This isn't as bad as it sounds because you can still get back typed results.
EDIT: After reading the other answers, it appears that it is possible to call these types of functions (SqlFunctions contains 44 functions with various overloads). I leave my original answer as is because it's another way of achieving the same result.