I'm wondering if there is any way to map a stored procedure result into into a class.
This is what I have:
// DbContext Class:
public DbSet<StoredProcedureModelResult> SPMR { get; set; }
// Service Class:
var result = ctx.Set<StoredProcedureModelResult>().FromSql("getXXXX p1 = {0},1).ToList();
This works well, however, I'm using database migrations and every time I add one this thing creates StoredProcedureModelResult as a table...
I tried to ignore it onModelCreating:
modelBuilder.Ignore<SPModels.test>();
but this throws an exception:
Cannot create a DbSet for 'StoredProcedureModelResult ' because this type is not included in the model for the context
I just want use the benefit of mapping, and not to get a table creation, this is a simple model (non-entityType)
BTW
.NET Core 1.1
Web API
EF Core (code-first)
Thank you
You don't need to make the type an Entity type (by registering a DbSet in your DbContext). Just have a method that returns IEnumerable<StoredProcResults> (can be in your DbContext), and in it run
dbContext.Database.SqlQuery<StoredProcResults>(...)
See Database.SqlQuery<T>(...)
Related
I am implementing Asp.Net core Web API , entity framework core, database first approach using Visual Studio 2017. I have managed to generate the context and class files based on an existing database. I need to access stored procedures using my context. In earlier version of entity framework it was simple by selecting the stored procedure objects in the wizard and generating an edmx that contains those objects. I could then access stored procedures via the complex type objects exposed by entity framework. How do I do a similar thing in entity framework core. An example would help ?
Database first approach is not there in EF Core with edmx files.Instead you have to use Scaffold-DbContext
Install Nuget packages Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore.SqlServer.Design
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
but that will not get your stored procedures. It is still in the works,tracking issue #245
But, To execute the stored procedures, use FromSql method which executes RAW SQL queries
e.g.
var products= context.Products
.FromSql("EXECUTE dbo.GetProducts")
.ToList();
To use with parameters
var productCategory= "Electronics";
var product = context.Products
.FromSql("EXECUTE dbo.GetProductByCategory {0}", productCategory)
.ToList();
or
var productCategory= new SqlParameter("productCategory", "Electronics");
var product = context.Product
.FromSql("EXECUTE dbo.GetProductByName #productCategory", productCategory)
.ToList();
There are certain limitations to execute RAW SQL queries or stored procedures.You can’t use it for INSERT/UPDATE/DELETE. if you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand
var categoryName = "Electronics";
dataContext.Database
.ExecuteSqlCommand("dbo.InsertCategory #p0", categoryName);
The above examples work fine when executing a Stored Procedure if you are expecting the result set to be the same as any object already defined. But what if you want a resultset that is not supported? According to the developers of EF Core 2, this is a feature that will come, but there is already today an easy solution.
Create the model you want to use for your output. This model will represent the output, not a table in the database.
namespace Example.EF.Model
{
public class Sample
{
public int SampleID { get; set; }
public string SampleName { get; set; }
}
}
Then add to your context a new DBSet with your model:
public virtual DbSet<Sample> Sample { get; set; }
And then do as above, and use your model for the output:
var products = _samplecontext.Sample
.FromSql($"EXEC ReturnAllSamples {id}, {startdate}, {enddate}").ToList();
I hope this helps anyone out.
My original post - https://stackoverflow.com/a/57224037/1979465
To call a stored procedure and get the result into a list of model in EF Core, we have to follow 3 steps.
Step 1.
You need to add a new class just like your entity class. Which should have properties with all the columns in your SP. For example if your SP is returning two columns called Id and Name then your new class should be something like
public class MySPModel
{
public int Id {get; set;}
public string Name {get; set;}
}
Step 2.
Then you have to add one DbQuery property into your DBContext class for your SP.
public partial class Sonar_Health_AppointmentsContext : DbContext
{
public virtual DbSet<Booking> Booking { get; set; } // your existing DbSets
...
public virtual DbQuery<MySPModel> MySP { get; set; } // your new DbQuery
...
}
Step 3.
Now you will be able to call and get the result from your SP from your DBContext.
var result = await _context.Query<MySPModel>().AsNoTracking().FromSql(string.Format("EXEC {0} {1}", functionName, parameter)).ToListAsync();
I am using a generic UnitOfWork & Repository. So my function to execute the SP is
/// <summary>
/// Execute function. Be extra care when using this function as there is a risk for SQL injection
/// </summary>
public async Task<IEnumerable<T>> ExecuteFuntion<T>(string functionName, string parameter) where T : class
{
return await _context.Query<T>().AsNoTracking().FromSql(string.Format("EXEC {0} {1}", functionName, parameter)).ToListAsync();
}
Hope it will be helpful for someone !!!
The workaround we use in EF Core to execute stored procedures to get the data is by using FromSql method and you can execute stored procedure this way:
List<Employee> employees = dbcontext.Employee
.FromSql("GetAllEmployees").ToList();
But for Create, Update, and Delete, we use ExecuteSqlCommand like the one below:
var employee = "Harold Javier";
dbcontext.Employee
.ExecuteSqlCommand("InsertEmployee #emp", employee);
The solution Rohith / Harold Javier / Sami provided works. I would like to add that you can create a separate EF6 project to generate the C# classes for resultsets and then copy the files to your EFCore project. If you change a stored proc, you can update the result file using the methods discussed here: Stored Procedures and updating EDMX
If you need corresponding typescript interfaces, you can install this VS2017 extension typescript definition generator: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.TypeScriptDefinitionGenerator
There are still be a couple of copying, but it is less tedious than creating the classes manually.
Edit: there is a VS2017 extension for generating the dbconext https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools. It does not do stored procedures, but it provides a right click menu item from VS project instead of the command line Scaffold-DbContext.
If you need to execute stored procedure in MySQL database from EntityFramework Core, the following code should work.
var blogTagId = 1;
var tags = await _dbContext.BlogTags.FromSqlRaw("CALL SP_GetBlogTags({0})", blogTagId).ToListAsync();
I have exposed some EF5.0 entities generated from a database through at WCF data service.
The data service is consumed by a WPF-client which takes the entities (from the data service) and store them locally. I do this by creating a code-first entity database based on the WCF-entities:
public class LocalRaceContext : DbContext
{
public LocalRaceContext() { }
public LocalRaceContext(string connstr) : base(connstr) { }
public DbSet<Participant> Participants { get; set; }
.
.
. more ...
}
I want to extend the Participant with a new property (in the client-side model). I figured I could just do this with a partial class like so:
public partial class Participant
{
public virtual List<Stamp> Stamps { get; set; }
}
This however does not work. Do I need some kind of attribute on the partial class?
I get the following error:
"The type 'RaceEntities+Participant' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject."
Edit:
#IronMan84: The original model (without the partial class) works because EF code-first takes care of the database and table creation. Actually it works perfectly fine and I am able to save the EF model in a local SQL CE file and retrieve the objects again as EF-classes later.
What I'm trying to achieve is to persist data from the data service locally but in a model which is somewhat extended. I've succeeded so far up until the extending part.
#Matt Whetton: It fails when I create a new instance of LocalRaceContext.
Edit2: I've tried to make an empty partial class (no properties). It still throws the same error.
Thanks in advance
Frederik
Nested classes are not yet supported by EF. Move the Participant class outside of RaceEntities.
One of my entity classes would be possible to store in a sql server
database as a BIGINT. My question is: How do I get a Entity Framework
context to know how to store and retrieve instances of my entity class?
More detail. I'm using Noda Time, which can represent a (much) wider range of
dates than can SQL or .NET datetime (AND it's a dessert topping). My Entity Class, Happening, is a wrapper around NodaTime's
Instant class. I can set a Happening from a long, and get a long from
a happening with methods like .SetFromLong(long instant) and .ToLong().
Currently I have my model working, saving classes that contain
properties of the dot net DateTime type. If instead I want to use properties
of my custom type "Happening", how do I tell Entity Framework how to save those?
If I'm reading this article about Modeling and Mapping am I on the
right track or missing something simpler?
http://msdn.microsoft.com/en-us/library/bb896343.aspx
I'm using entity framework 4.
What i recommend doing is adding 2 properties on your entity a NodaTime and a long, and exclude your NodaTime property using [NotMapped] in your EF model, then in your getter/setter update the long.
ie
public class MyEntity{
public long TimeAsLong{get;set;}
[NotMapped]
public Happening {
get{
return new Happening().SetFromLong(TimeAsLong);
}
set {
TimeAsLong = value.ToLong();
}
}
}
The effect of this will be that the long is stored in the db but you can access it on the class via NodaTime
I'm using VS1010RC with the POCO self tracking T4 templates.
In my WCF update service method I am using something similar to the following:
using (var context = new MyContext())
{
context.MyObjects.ApplyChanges(myObject);
context.SaveChanges();
}
This works fine until I set ConcurrencyMode=Fixed on the entity and then I get an exception. It appears as if the context does not know about the previous values as the SQL statement is using the changed entities value in the WHERE clause.
What is the correct approach when using ConcurrencyMode=Fixed?
The previous values need to be in your object.
Let's say you have a property ConcurrencyToken:
public class MyObject
{
public Guid Id { get; set; }
// stuff
public byte[] ConcurrencyToken { get; set; }
}
Now you can set ConcurrencyMode.Fixed on that property. You also need to configure your DB to automatically update it.
When you query the DB, it will have some value:
var mo = Context.MyObjects.First();
Assert.IsNotNull(mo.ConcurrencyToken);
Now you can detach or serialize the object, but you need to include ConcurrencyToken. So if you're putting the object data on a web form, you'll need to serialize ConcurrencyToken to a string and put it in a hidden input.
When you ApplyChanges, you need to include the ConcurrencyToken:
Assert.IsNotNull(myObject.ConcurrencyToken);
using (var context = new MyContext())
{
context.MyObjects.ApplyChanges(myObject);
context.SaveChanges();
}
Having ConcurrencyMode.Fixed changes the UPDATE SQL. Normally it looks like:
UPDATE [dbo].[MyObject]
SET --stuff
WHERE [Id] = #0
With ConcurrencyMode.Fixed it looks like:
UPDATE [dbo].[MyObject]
SET --stuff
WHERE [Id] = #0 AND [ConcurrencyToken] = #1
...so if someone has updated the row between the time you read the original concurrency token and the time you saved, the UPDATE will affect 0 rows instead of 1. The EF throws a concurrency error in this case.
Therefore, if any of this isn't working for you, the first step is to use SQL Profiler to look at the generated UPDATE.
Mark,
The objects created as "Self-tracking entities" cannot be considered pure POCOs;
Here's the reason:
The STEs only work well if your client uses the generated proxies from the STE T4 template.
Change-tracking, and thus your service, will only work with these generated proxies.
In a pure POCO world (interoperatibility, Not all .Net 4.0 clients, .. ), you cannot put
constraints on you client. For instance, facebook will not be writing a service that can
only handle .Net 4.0 clients.
STEs may be a good choice in some environments, it all depends on your requirements.
I have a project where the client is using Entity Framework, and I'm trying to abstract away the generated classes from the rest of the application.
One generated class is Category and it has say Type as a property.
I've created an interface that I want Category to implement, like this:
public interface ICategory
{
string Type { get; set;}
}
I have done this in LINQ to SQL before and it works fine. I create a partial class in a separate file and have it implement the interface:
public partial class Category: ICategory
//implement interface
However, with EF whenever I try to build a query with EF it says it doesn't support OfType<>().
Example:
var query = from c in DataContext.Category
where Type == "some type"
select c;
var resultsList = query.OfType<ICategory>(); //error here (not supported)
What am I doing wrong here?
Other things to note: I'm developing this in a silverlight application and the data context is actually being pulled from a service, so there's a client server relationship going on here as well.
As a general rule, LINQ to Entities can only understand things which are part of your entity model (EDMX). So while you are free to extend your entity types be a partial classes, you cannot use properties, methods, and interface references you add there in LINQ to Entities queries, except for certain, very specific features.
However, in this case the following query should give you the result you want:
var resultsList = query.Select<ICategory>(c => c);