Is there a way to map a stored procedure to Entity Framework in such a way that the ExecuteFunction uses the MergeOption parameter with the NoTracking option?
You could update the T4 template file to add "MergeOption.NoTracking" as the 2nd parameters. Then just R-Click on the .edmx and select "Run Custom Tool".
This is a quick workaround but I would also like to know a more long term solution. If this is the only solution, can the default T4 templates be updated so that this is automatic with new EntityModels and were are they stored.
{EnitityModel}.Context.tt
Line 290:
"return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\", MergeOption.NoTracking{2});",
I was setting the following in my Repository constructor, but the MergeOption appears to be cleaner
context = new Entities();
context.Configuration.AutoDetectChangesEnabled = false;
context.Configuration.ValidateOnSaveEnabled = false;
Related
Is it possible to add a column (or execute some SQL) to a table when Entity Framework is instantiating a new database, without defining it in the Model used in DbSet ?
Iam building a prototype for a SaaS application with Entity Framework and Elastic Scale Client, and want to use Row Level Security, for that a need a column to identify my tenants. So i figured it would be nice if I could use just the EF initializer to add this column, when adding new tenants to the system.
As noted in the documentation here, you can execute sql when you have the DBContext.
From the docs:
using (var context = new BloggingContext())
{
context.Database.ExecuteSqlCommand(
"UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}
You could use this to modify the structure without having the actual structure defined in EF.
I have a ASP.NET MVC5 project with EF6. In SQL server 2008 I have a stored procedure that takes 2 parameters, an ID and a language ID, and returns data based on the parameters.
I want to call this stored procedure in one of my controllers to view the data. But I don't know how to do this. Can anybody help me or provide a tutorial for it?
I have the stored procedure in the project as an ADO.NET entity object already, it has a model class and such thus.
You can use Entity Framework's ExecuteSqlCommand to achieve this:
SqlParameter param1 = new SqlParameter("#param1", "Item1");
SqlParameter param2 = new SqlParameter("#param2", "Item2");
context.Database.ExecuteSqlCommand(
"sp_StoredProcedureName #param1, #param2",
param1,
param2);
I would like to pass a connection string to the constructor of DbContext. The way to do this has been answered here: Pass connection string to code-first DbContext
(code if you don't like to click)
public MyContext(string connString)
: base(connString)
{
}
However, when I attempt to enable migrations I receive the error: "The target context '...' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."
Also, when I attempt to use EF PowerTools to generate an Entity Data Model is receive the error: "A constructible type deriving from DbContext could not be found in the selected file."
Is this a common problem? I have a fix, but it feels like a hack. Any one else have to deal with this before?
Add also an empty constructor, e.g...
public MyContext()
{
}
Thing is once you define a parametrized ctor your default one gets hidden
e.g. see Why does the default parameterless constructor go away when you create one with parameters
That's also one way of 'hiding' default construction from the outside users.
Usually you don't even expose that 'other' ctor to the outside - as its 'yours', you just hardcode inside what you need. Or alternatively and better - you use the 'app.config' to specify the connection string. For details (and problems with it) see...
Migration does not alter my table
Migration not working as I wish... Asp.net EntityFramework
I'm using Entity Framework 4. I am using a database first model, meaning that I generated the EDM from the database. Now I want to add some model-defined functions. My question is ... where?
If I put them in the .edmx file, won't all my additions be clobbered the next time I update the database and generate the new EDM? I mean it says it right there at the top of the .Designer.cs file, "Manual changes to this file will be overwritten if the code is regenerated."
So, in what file do I put my additions?
I will take it little bit deeply because model defined functions are not very well known.
Model defined functions must be manually added to CSDL part of EDMX file. You must open file as XML and add a function. For example this model defined function is able to produce full name of the employee:
<Function Name="FullName" ReturnType="Edm.String">
<Parameter Name="emp" Type="TestModel.Employee" />
<DefiningExpression>
Trim(emp.FirstName) + " " + Trim(emp.LastName)
</DefiningExpression>
</Function>
Now you can save your EDMX and return to designer. The function will be still present but it is not visible in Model browser. You can update your model from database or delete all your entities but the function will be still defined. EF doesn't remove custom modification in CSDL part of EDMX.
Now you need to define the .NET function to be able to use this model defined function. You can do it anywhere. One way is to use partial class to context but in the same time you can just use some custom class:
public static class EdmFunctions
{
[EdmFunction("TestModel", "FullName")]
public static string FullName(Employee e)
{
throw new NotSupportedException("This function is only for L2E query.");
}
}
And you are done. The only remaining task is using the function in Linq-to-Entities query:
using (var context = new TestEntities())
{
var query = from e in context.Employees
select new
{
e.Id,
FullName = EdmFunctions.FullName(e)
};
var data = query.ToList();
...
}
Model defined functions are just some reusable Entity SQL which is translated to SQL so they can be only used in Linq-to-Entities queries. Model defined functions can be much more complicated.
New to Entity Framework .Using EF4. I have found articles and managed to use stored procedures to return a list of entities.
But cannot see/work out how you return a single entity.
Given that I have a stored procedure "GetCustomerById" that return a single customer How do I map it?
Using the Model Browser I right click on "Function Import" and I have added my StoredProcedure
however whatever I select does not seem to return a "Single Entity"
Am I missing the obvious?
thanks a lot for any link or suggestions
When you do Function Import you need to select the entity your SP returns from the drop down (i.e. Customer). The catch is EF does NOT directly returns Customer object as per your selection but System.Data.Objects.ObjectResult which implements IEnumerable.
To be more specific, here is the generated code for your function:
public ObjectResult<Customer> GetCustomerById(Nullable<global::System.Int32> Id)
That's because EF has no idea if your SP returns a single record or a list of them so it wraps the result inside ObjectResult. You can enumerate through this to get your Customer entity like any other IEnumerable object. For example:
Customer myCustomer = context.GetCustomerById(1).First();