Is there a CLR data type to Sql data type translation method? - clr

I was going through the MVC material over at asp.net, and came across the 5 minute introduction video:
http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc
In this video, there was demonstration of creating a model, then having MVC generate a Sql table based on the object/model automatically.
My question is, what mechinism is used to translate the object's CLR datatypes to Sql Server datatypes?
I'd like to create a quick and dirty method to have similar functionality outside of MVC... something as simple as a method returning a Create Table string.

Like this maybe?
MSDN - Mapping CLR Parameter Data
Or this?
MSDN - SQL-CLR Type Mapping (LINQ to SQL)

Related

Entity Framework Core Database Table Valued Functions Mapping

I use EFCore 2.1 Database First approach. I'm pretty familiar with SQL syntax and prefer build queries myself rather then leave this work on EF. I use Table Valued and Scalar Functions for querying the database.
I found this for Scalar
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#database-scalar-function-mapping
But unfortunately nothing about Table Functions.
Is there any way to force Visual Studio grab all Table Functions and Scalar Functions and Stored Procedures from SQL Server, when I run Scaffolding?
I was using LINQ to SQL dbml designer before. Everything was extremely simple with dbml. You drag from Server Explorer drop to dbml and boom, I can use SQL Function or SP like regular C# method.
Any chance to reproduce this in EFCore?
There's no reverse engineer (aka DbContext scaffolding) support for it, but you can use FromSql() to query using table-valued functions. See these docs.
var searchTerm = "EF Core";
var blogResults = db.Blogs.FromSql(
"SELECT * FROM dbo.SearchBlogs({0})",
searchTerm);
Source : https://www.allhandsontech.com/data-professional/entityframework/entity-framework-core-advanced-mapping/
Use HasDbFunction to do a mapping, refer Microsoft doc
It requires return types to be declared as Keyless entity using HasNoKeyMicrosoft doc
Configure EF Context to expose Db function
modelBuilder.HasDbFunction(typeof(SalesContext)
.GetMethod(nameof(NameAndTotalSpentByCustomer)))
.HasName("CustomerNameAndTotalSpent");
modelBuilder.Entity<CustWithTotalClass>().HasNoKey();
Invoke Db function in calling code
_context.NameAndTotalSpentByCustomer().Where(c=>c.TotalSpent>100).ToList();
Generated SQL
SELECT [c].[Name], [c].[TotalSpent]
FROM [dbo].[CustomerNameAndTotalSpent]() AS [c]
WHERE [c].[TotalSpent] > 100

How to access Stored procedure in Code First Model which return 6 or 7 table combine result

i am new in MVC and entity frame work and i want to create Code first entity frame work.
we have already created project in asp.net and we want to migrate in mvc. we have lots of stored procedure and some procedure return complex data combination of 10 to 12 tables...
As a Proof of Concept we wan't to develop 3 to 4 pages...
i have some question regarding new start.
1) Should i used entity frame work if yes then which is better entity frame work model
Database first
Model first
code first
2) how to integrate stored procedure in Code first model
3) in each page we have minimum 7 to 8 table result there... how i will handle in entity frame work.
this is my first project in mvc and entity framework please help me with appropriated answer.
first, this has nothing to do with MVC. this is purely a data access issue.
second, this is sort of missing the point of using entity framework. if the goal is to migrate away from stored procs that one thing, but to use EF and continue to execute the stored procs defeats the purpose of using a ORM like EF.
Instead for your procs I would stick with raw ADO.Net, or use Dapper.Net to convert the stored proc result sets into objects.
EF would be a better choice as your convert each proc into EF linq queries. It's not that you can't execute procs (or raw sql) from EF, but it doesn't make much sense. Especially with how you describe the procs.

Using EF and MVC together

I would like to use Entity Framework 5 from which I can use one MVC Model that can span two or more databases.
Is this possible?
In other words, have one EF model that can use two or more databases. Because with MVC, you can only use 1 model in a View. Some of the data with some of the Views can come from different databases. In order to use the model binder in MVC and map it to EF 5 columns, I would need to accomplish this.
ASP.NET MVC is NOT dependent on Entity Framework.
ASP.NET MVC is a framework for building web application that stick with the Model View Controller pattern. It is not bounded to Entity framework. It can work with any data access technologies like LINQ2SQL / Entity Framework / Pure ADO.NET etc.. that means you can develop MVC application with or without using Entity Framework.
I assume you want to get data from 2 different databases and load a model object. You can do that by writing a select query which gets data from 2 databases and put that in a Stored procedure and put that proc in your database which your DbContext is communicating with. Then execute the stored proc and load the Model object.
a sample procedure which gets data from 2 databases
CREATE PROCEDURE GetCustomer(#id int)
AS
BEGIN
SELECT C.ID,A.DateReceived
FROM FirstServerName.DbName.dbo.Customer C
INNER JOIN SecondServerName.DbName.dbo.Applications A
ON A.CustomerID=C.CustomerID
AND A.CustomerID=#id
END
To execute the stored proc with Entity framework, you can use Database.SqlQuery method
var idParam = new SqlParameter { ParameterName = "#Id", Value = 414};
var result = context.Database.SqlQuery<Customer>
("exec GetCustomer #Id", idParam).ToList();
This will execute your proc and load the data to an instance of Customer class, assuming the result set structure and your model class structure look similar.
You may need to adjust the permissions of the stored proc to read data from the relevant databases /tables.
What Shyju is saying is that MVC doesn't care or know anything about your Entity Framework data model or database. As such, the idea that an MVC model can span two databases is like saying an airplane can span two hammers.
As above the M in MVC is whatever you want it to be. Microsoft don't specify what Model actually is. It certainly doesn't have to be an EF Model (although some code samples from MS use that as an example)
I'd suggest that M should be a ViewModel and should be unrelated to your data layer. Then use a tool like Automapper to map from a domain model to a ViewModel. The ViewModel encapsulates the data you want to show and any specific web view specific information that you want to display. Then when you post back the ViewModel you can use that to update the domain models appropriate fields etc and persist that to both databases. This is a good article on the subject of ViewModels http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

Entity Framework 4: Math.Sin()-function

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.

SubSonic 2.x StoredProcedure parameter data types?

From what I can see, SubSonic 2.x stored procedure parameter data types can only be of type System.Data.DbType.
Is there a quick way to add System.Data.SqlDbType so we can use System.Data.SqlDbType.Structured to pass tables - ultimately to TVP's?
In this particular project, all data caller functions are accessed through StoredProcedures.cs. If we switched to 3.x, does it support SqlDbType.Structured, and if so, is it a seamless integration to retain the current StoredProcedures.cs methods?
You should take a look here. Some guy with the same username and an identical avatar image just implemented that ;)
So, I created my own solution for this - SubSonic 2.x now supports TVP's - SqlDbType.Structure / DataTables for SQL Server 2008
I'm somewhat surprised at the lack of response to TVP's, and seemingly low traction TVP's have in online communities.

Resources