Combination of code first and database first approach - asp.net-mvc

Is it possible that we can use entity framework power tool to import pre created stored procedures but this should be in code first approach.
What I am think is that
1) I will create a code first project.
2) With entity framework power tool i will generate edmx from context.
3) I will import my stored procedures.
4) I will provide sql script which will create stored procedure with SQL() function in migration.
5) The next time when a fresh database is used, the procedure will be created from script and it will be mapped with edmx.
Please provide any details about it.

Related

Add SQL function into project with EF6

I want import my function from SQL Server into my ASP.NET MVC project with EF6 database first.
My problem is when I update database in .edmx file, based on what I found in the sources, I open Model Browser but in this file I can't use "Add function import" because stored procedure / function name is empty.
What do you think? What is my mistake?
Finally I couldn`t find what was the problem, but I got answer by this solution :
I create an stored procedure and called my function in it. after that I added stored procedure in my project as easy as possible.

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

Stored procedure not appearing in EF code

I'm using EF database first and have added a stored procedure to the database.
When I ran Update model from database on the edmx file it picked up the stored procedure and I selected it as an item I wanted to include.
I have a file named Model<projectname>.Context.cs with a class called Entities in it. This is an auto-generated class and it contains methods for other stored procedures in the system. My new stored procedure does not have a corresponding method in this class and running Run custom tool does not help.
Is there something else that I need to do, that I am not doing?
Thanks,
Sachin
EDMX doesn't support Table-valued parameter. So if your proc uses the TVP as the parameter, the EDMX designer can't pick it up.
Edited:
If you want to retrieve the result set and create object/POCO for the proc, then just simply remove the tvp, compile the proc, let the EDMX designer to pick up your proc, generate the result object and then add the tvp back to your proc. This is a very easy way to cheat the EDMX designer and get what you need.
Ensure you are doing "Run Custom Tool" on the *Model.CONTEXT.tt file.

HOw can I access two database in single .edmx file?

I have created mvc3 application.
I have one .edmx already created which is based on Db1 but now
I have created a view which is based on Database2 and I need to use this view inside my project.
For that I need to update my EF .edmx file.
but when I right click and select option Update model from Database
i'm only getting all tables , view ,sps fromDb1` its obvious
But as i need to use view which is fromDatabase2how can i add it into my model.edmx` file?
please help.
If two edmx want to merge then make partial class same for both edmx file (there will be two designer classes). Add another constructor and make it parametrized, for other edmx file. Parameter to identify which edmx want to load.
Add another class file in Business layer create object of edmx partial class in this class file, Under this class when ever you want to load whom so ever edmx file pass some argument in constructor of edmx partial class constructor to identify which connection needs to open.
Pass parameter in constructor of edmx designer class, based on decided page name (custom logic or table name; That edmx will get loaded.
In web config file multiple connection strings will available for multiple edmx file.
Entity Framework does not support mapping more than one database to one model/.edmx file (see See : unify two models (edmx) with visual studio 2010)
So you'd need to create a separate .edmx file/model for the other database, and reference each model with separate contexts. You'll need 2 connection strings in your projects as well.
One "hack" might be, for i.e. MS SQL to link these two servers and expose the data from other one on first one, i.e. via view. But I think it's manageable only for few tables. With huge models this will be pain. Other databases (Firebird, Oracle, ...) support this in similar way.
What I have done , created stored procedure in db A and accessed the db B through that SP , say select * from db2.table.then create a function import for that particular SP .
This approach works well if you have both databases on same server. In case these are on different servers you can create Linked Server on B to access A using the same stored procedure approach.
Using ctx As New Entity()
ctx.Database.Connection.ConnectionString = conString
End Using

Understanding VS's ability to create database on first run

I'm working with a (.net4 / mvc3 ) solution file downloaded (from a reputable source) where a connection string exists in web.config but I don't see explicit instructions to create the database and there's no included '.mdf'. The first time I build I got a runtime error regarding lack of permissions to CREATE database. So I created a blank db and made sure the string referenced a SQL user that had .dbo/owner rights to the db just created.
But subsequent builds don't seem to execute that same initialize db script - where ever that's stored.
Where is this 'first use' convention for creating databases documented?
thx
That is a feature of Entity Framework Code First. I am not sure what you are looking for exactly, but searching for "EF Code First Initialization Strategy" might help.
For instance read this article: EF Code First DB Initialization Using Web.Config
I assume you are talking about Entity Framework, which allows you to create the database from an instance of an ObjectContext object, which is used in any of the three approaches in EF (database-, model- and code-first).
Look for a line that actually calls ObjectContext.CreateDatabase(). If one of the supported ADO.NET provides is used (SQL Server or SQL Server CE 4.0) this will generate the required SQL Statements. Assuming the classic Northwind example, you might find something like that:
NorthwindContext context = new NorthwindContext();
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
If this is in fact a code-first application, "lalibi" is right about the initialization strategy which by default doesn't require you to explicitly create the database. (But my guess is, that it actually uses a statement internally very similar to mine).

Resources