entity framework ctp5 get unproxied entity - entity-framework

EF CTP 5. I have a single instance where I would like to get the unproxied entity. I can't seem to find a way to do this. I don't want to disable proxy creation all together, just need it for this one query. Can anyone help?
Here is a simple example:
var myEntity = DbContext.Entities.Find(1);
var unproxy = myEntity...?

I believe the only possibility is to create new instance of DbContext and turn proxy creation off just to execute this query. The reason is that DynamicProxy is type created in runtime which derives from your original entity type and adds tracking and lazy loading functionality. You can't strip the proxy away once you created it this way. Try this:
using (var context = new MyDbContext(connectionString))
{
((IObjectContextAdapter)context).ObjectContext.ContextOptions.ProxyCreationEnabled = false;
var myEntity = context.Entities.Find(1);
}

In Asp.Net Core you can use AsNoTracking().
Eg:
var blogs = context.Blogs
.AsNoTracking()
.ToList();
More info you can find here.

Related

Entity Framework new object vs DbSet.Create

We are migrating a web application from EF 4.0 to EF 6. The entities were earlier based on ObjectContext, but now we are looking at DBContext. The code heavily depends on lazy loading. Entities are added using following syntax:
var user = new EntityModel.User();
user.DepratmentId=25;
context.Users.Add(user);
context.SaveChanges();
var name = user.Department.Name;
the original code would easily assign department name into variable name. After Entity framework upgrade to EF6 with DBContext, user.Department is null. I understand that when we are using DBContext, Lazy Loading works only with Proxies. It would work fine if the code was changed to following:
var user = context.Users.Create();
user.DepratmentId=25;
context.Users.Add(user);
context.SaveChanges();
var name = user.Department.Name;
Problem at my hand is that we can not make this change in the whole code base. Given the large volume of code, this is practically impossible. Does someone have a solution to this?
Provided your entities are easily identifiable such as all being pulled from the namespace "EntityModel" then VS's Find & Replace can help with the transition. Ultimately you're going to have to eat the cost of that technical debt. Re-factoring isn't free, but the benefit from making improvements (beyond just upgrading a dependency version) should outweigh that cost.
Using Find & Replace:
Find: = new EntityModel.(?<class>.*)\(\)
Replace: = context.${class}s.Create()
This will find instances like:
var user = new EntityModel.User();
and replace it with var user = context.Users.Create();
a test with:
var user = new EntityModel.User();
var test = new EntityModel.Test();
var fudge = new EntityModel.Fudge();
resulted in:
var user = context.Users.Create();
var test = context.Tests.Create();
var fudge = context.Fudges.Create();
Now this will extract the class name and pluralize it with an 's' which likely won't match 100% of the entity DBSet names, but those are easily found and corrected. The expressions can be tuned to suit differences through the application and I would recommend performing the operation on a file by file, or at most project by project basis.
An caveat is to make sure you're running with source control so that any bad attempts at a replace can be rolled back safely.

Entity framework connection string reference from another project

I have a solution consisting of 4 projects. MVC, WCF, Business LYR, DataAcess. I am using entity framework for database transaction. My requirement is that i want to fetch the entity connectionstring only from MVC webconfig without refering in APP.cofig of acess layer. Is it possible in this scenario?
While I tried the following code I got an error.
this.ConnectionString="data source=cmh-sosql;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(this.ConnectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/schoolModel.csdl|res://*/schoolModel.ssdl|res://*/schoolModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
using (SchoolDB schoolDB = new SchoolDB(ecb.ConnectionString))
Error: The entity type student is not part of the model for the current context.
You are absolutely correct. I got the solution. There is no need to keep any string in webconfig for reference to a entity model. We can use the above code for reference it. But the change is to configure the context object.
public SchoolDB(string connectionString)
: base(connectionString)
{
}
We need to change the constructor also by this format.
thanks Sampath

How do I foreach through my dbcontext entities in EF 4.1?

I'm using ASP.NET Entity Framework 4.1 MVC 3 (C#)
I want to foreach through all the entities in my DbContext. I need to be able to dynamically refer to my entities in order to make dynamic views.
I have read Lerman's book, two MVC (2 & 3) books, msdn, asp.net, etc. Maybe I am just missing something?
It seems like you might have to use ObjectContext to get to the entities. If that is the right way, I sure can't figure out how to do it. Please help. Thank you.
you can also do this(for example):
foreach (var dbItem in dbContext.Items)
{
//do what you want inside the loop with the dbItem
sList.Add(new SelectListItem() {Text = dbItem.ItemName, Value = dbItem.ItemTag});
}
I am not exactly sure what you are asking. If you want to dynamically reference the DbSets inside of DbContext you could use reflection:
DatabaseContext context = new DatabaseContext();
var contextObject = context as Object;
var contextType = contextObject.GetType();
var properties = contextType.GetProperties();
String result = String.Empty;
foreach (var property in properties)
{
result += property.Name + "\n"
{
But to be perfectly honest, I do not know what you are asking or what you want. I just saw you had no answers yet so I thought I would give my two cents.
Form your query using Entity Sql and a call to CreateQuery.
See if this gets you started.
http://www.codeproject.com/Questions/208209/Problem-with-Entity-SQL?display=Print
ObjectQuery query = ctx.CreateQuery("SELECT P FROM WebStoreEntities.Customers AS P");
Im not 100% sure how to get the names of the entities - try OpticalDelusions way - but this may help once you have them.
You'll have to dynamically put everything together - but the resulting type you may have a problem casting around, but give it a try.

ASP.NET MVC2 Posting a ViewModel mapping to Domain (LINQ) to Submitting changes

I'm using AutoMapper to map between a Linq Domain object and a ViewModel to display an Edit Form to the user which works perfectly.
When they click submit I'd like to know the best way to map the ViewModel back to a Linq entity and persist it to the database.
The Linq entity I'm using has multiple collections of other entities (ie one-to-many references).
I was trying:
build up my custom view model using UpdateModel
get the previous state of the Linq entity by using the passed in id
map the view model onto the Linq entity (using automapper)
call SubmitChanges() on the data context
This method works when I'm only updating properties that are not collections, but throws errors when trying to modify properties that are collections.
Any help/thoughts would be much appreciated :)
I've taken an approach that is very similar to that used by Jimmy Bogard in the CodeCampServer project (http://codecampserver.codeplex.com/)
I have a general Mapper class that I inherit from where I just need to override a MapToModel method that maps from the ViewModel to the domain Model, and a GetIdFromViewModel method that returns the proper Id form the ViewModel so that the Service layer can grab the domain model from the database.
I had to change a little from the CodeCampServer examples because some of my Models used Guid and some used int as the Id for the Model.
You should be able to grab the code from the codeplex link above and that should help get you going in that direction.
Here is what one of my Mappers for a Member looks like:
public class MemberMapper : AutoFormMapper<Member, MemberFormViewModel, Guid>, IMemberMapper
{
public MemberMapper(IMemberService service) : base(service) { }
protected override Guid GetIdFromViewModel(MemberFormViewModel viewModel)
{
return viewModel.MemberId;
}
protected override void MapToModel(MemberFormViewModel viewModel, Member model)
{
// if the need arises, we will need to map the full objects as Foreign Key properties
// by using the proper repositories
// right now for loading the object to save back to the DB we don't have that need, so let's not waste the call
model.MemberId = viewModel.MemberId;
model.FirstName = viewModel.FirstName;
model.LastName = viewModel.LastName;
model.Title = viewModel.Title;
model.EmailAddress = viewModel.EmailAddress;
model.DirectPhone = viewModel.DirectPhone;
model.MobilePhone = viewModel.MobilePhone;
model.ElectronicId = viewModel.ElectronicId;
model.ProjectRoleTypeId = viewModel.ProjectRoleTypeId;
model.DepartmentId = viewModel.DepartmentId;
}
}
Then you can use this MemberMapper to map both directions. It uses AutoMapper to go from the domain Model to the View Model and then uses the MapToModel method that you implement to map from the View Model back to the domain Model.

How to use ADO.net Entity Framework with an existing SqlConnection?

I have an existing asp.net website that uses an SqlConnection.
I have added the ADO.net Entity Framework.
I have successfully connected to the database and created the .edmx file.
I am able to connect through the Entity Framework with the connectionstring that is automatically generated.
I want to use the existing SqlConnection object that I use throughout the site for the Entity Framework connection.
I do not want to have to use a second database connection for the one page that is going to use the ADO.net Entity Framework and I don’t want to change the entire site to use the new Entity Framework connection string.
Thanks for any help you can provide.
That forum post has the answer:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection))
using (NorthwindEntities context = new NorthwindEntities(entityConnection))
{
foreach (var product in context.Products)
{
Console.WriteLine(product.ProductName);
}
}
"res://*/" is the part of your EF connection string that describes the location of your xml mapping files - in this case embedded resources in the current assembly.
You can do this by using the constructor of your generated ObjectContext that accepts an EntityConnection. When you create the EntityConnection you pass in your SqlConnection.
Andrew Peters,
Thank you for your answer.
I have been going around and around with the System.Data.EntityClient.EntityConnection.
It’s right there at my finger tips but I cannot seem to get the MetadataWorkspace parameter to work.
This is the closest example I have found (the post marked Answer):
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/dd7b1c41-e428-4e29-ab83-448d3f529ba4/
Thanks for any help.