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

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.

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.

Problem with EF STE and Self-Referencing tables

This is my first post here, so I hope everything is fine.
Here is my problem:
I have a table in my database called UserTypes. It has:
ID;
IsPrivate;
Parent_ID;
The relevant ones are the first and the third one.
I have another table called UserTypes_T which has information for the different types, that is language specific. The fields are:
Language_ID;
UserType_ID;
Name;
What I'm trying to achieve is load the entire hierarchy from the UserTypes table and show it in a TreeView (this is not relevant for now). Then, by selecting some of the user types I can edit them in separate edit box (the name) and a combo box (the parent).
Everything works fine until I try to persist the changes in the database. EF has generated for me two entity classes for those tables:
The class for the user types has:
ID;
IsPrivate;
Parent_ID;
A navigational property for the self-reference (0..1);
A navigational property for the child elements;
Another navigational property for the UserTypes_T table (1..*);
The class for the translated information has:
UserType_ID;
Language_ID;
Name;
A navigational property to the UserTypes table (*..1);
A navigational property to the Languages table (*..1);
I get the data I need using:
return context.UserTypes.Include("UserTypes_T").Where(ut => ut.IsPrivate==false).ToList();
in my WCF Web service. I can add new user types with no problems, but when I try to update the old ones, some strange things happen.
If I update a root element (Parent_ID==null) everything works!
If I update an element where Parent_ID!=null I get the following error:
AcceptChanges cannot continue because the object’s key values conflict with another object in the ObjectStateManager.
I searched all over the internet and read the blog post from Diego B Vega (and many more) but my problem is different. When I change a parent user type, I actually change the Parent_ID property, not the navigational property. I always try to work with the IDs, not the generated navigational properties in order to avoid problems.
I did a little research, tried to see what is the object graph that I get and saw that there were lots of duplicate entities:
The root element had a list of its child elements. Each child element had a back reference to the root or to its parent and so on. You can imagine. As I wasn't using those navigational properties, because I used the IDs to get/set the data I needed, I deleted them from the model. To be specific I deleted points 4 and 5 from the UserTypes entity class. Then I had an object graph with each element only once. I tried a new update but I had the same problem:
The root element was updated fine, but the elements, that had some parents, threw the same exception.
I saw that I had a navigational property in the UserTypes_T entity class, pointing to a user type, so I deleted it too. Then this error disappeared. All the items in the object graph were unique. But the problem remained - I could update my root element with no problems, but when trying to update the children (with no exclusions) I got a null reference exception in the generated Model.Context.Extensions class:
if (!context.ObjectStateManager.TryGetObjectStateEntry(entityInSet.Item2, out entry))
{
context.AddObject(entityInSet.Item1, entityInSet.Item2);//here!
}
I tried to update only the name (which is in UserTypes_T) but the error is the same.
I'm out of ideas and I've been trying to solve this problem for 8 hours now, so I'll appreciate if someone gives me ideas or share their experience.
PS:
The only way I succeeded updating a child object was using the following code to retrieve the data:
var userTypes = argoContext.UserTypes.Include("UserTypes_T").Where(ut => ut.IsPrivate==false).ToList();
foreach (UserType ut in userTypes)
{
ut.UserType1 = null;
ut.UserTypes1 = null;
}
return userTypes;
where UserType1 is the navigational property, pointing to the parent user type and UserTypes1 is the navigational property, holding a list of the child element. The problem here was that EF "fixups" the objects and changes the Parent_ID to null. If I set it back again, EF sets the UserTypes1, too... Maybe there is a way to stop this behavior?
OK everybody, I just found what the problem was and I'm posting the answer if anybody else encounters the same issue.
The problem was that I was making some validation on the server in order to see if there isn't a circular reference between the user types. So, my method on the server looked something like:
using (MyEntities context = new MyEntities())
{
string errMsg = MyValidator.ValidateSomething(context.UserTypes,...);
if (!string.IsNullOrEmpty(errMsg)) throw new FaultException(errMsg);
//some other code here...
context.UserTypes.ApplyChanges(_userType);//_userType is the one that is updated
context.UserTypes.SaveChanges();
}
The problem is that when making the validation, the context is filled and when trying to save the changes, there are objects with the same key values.
The solution is simple - to use different context for validating things on the server:
using (MyEntities validationContext = new MyEntities())
{
//validation goes here...
}
using (MyEntities context = new MyEntities())
{
//saving changes and other processing...
}
Another one can be:
using (MyEntities context = new MyEntities())
{
using (MyEntities validationContext = new MyEntities())
{
//validation
}
//saving changes and other processing...
}
That's it! I hope it can be useful to somebody!

entity framework ctp5 get unproxied entity

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.

XML serialization errors when trying to serialize Entity Framework objects

I have entities that I am getting via Entity Framework. I'm using Code-First so they're POCOs. When I try to XML Serialize them using XmlSerializer, I get the following error:
The type
System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127
was not expected. Use the XmlInclude
or SoapInclude attribute to specify
types that are not known statically.
Anybody got any ideas on how to get around this (short of creating a whole new object)?
Just saying POCO doesn't really help (especially in this case since it looks like you're using proxies). Proxies come in handy in a lot of cases but make things like serialization more difficult since the actual object being serialized is not really your object but an instance of a proxy.
This blog post should give you your answer.
http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx
Sorry, I know I'm coming at this a bit late (a couple YEARS late), but if you don't need the proxy objects for lazy loading, you can do this:
Configuration.ProxyCreationEnabled = false;
in your Context. Worked like a charm for me. Shiv Kumar actually gives better insight into why, but this at least will get you back to work (again, assuming you don't need the proxies).
Another way that works independent of the database configuration is by doing a deep clone of your object(s).
I use Automapper (https://www.nuget.org/packages/AutoMapper/) for this in my code-first EF project. Here is some sample code that exports a list of an EF objects called 'IonPair':
public bool ExportIonPairs(List<IonPair> ionPairList, string filePath)
{
Mapper.CreateMap<IonPair, IonPair>(); //creates the mapping
var clonedList = Mapper.Map<List<IonPair>>(ionPairList); // deep-clones the list. EF's 'DynamicProxies' are automatically ignored.
var ionPairCollection = new IonPairCollection { IonPairs = clonedList };
var serializer = new XmlSerializer(typeof(IonPairCollection));
try
{
using (var writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, ionPairCollection);
}
}
catch (Exception exception)
{
string message = string.Format(
"Trying to export to the file '{0}' but there was an error. Details: {1}",
filePath, exception.Message);
throw new IOException(message, exception);
}
return true;
}

Entity framework attach update not working

I'm trying to update a POCO object using entity framework in the following way:
context.Jobs.Attach(job);
context.SaveChanges();
That does not work. No error is thrown, it just isn't updating the values in the database.
I tried:
context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();
Nothing wrongs, still no error and no updates.
What about changing the ObjectState?
context.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);
From MSDN: ObjectStateManager.ChangeObjectState Method.
I guess you are working with detached object - check second part of this answer.
another reason that this may not work is when the corresponding Jobs.cs file has been committed but the .edmx file has not. This means that the property is present but not mapped and therefore EF does not consider the object modified. For example:
...
using (var dao = new DbContext())
{
dao.Jobs.Attach(job);
job.SomeProperty = 1234; // SomeProperty exists but is not in the .edmx
dao.SaveChanges();
}
if SomeProperty is present in Jobs.cs but missing from the .edmx file, this code will compile and execute without a hint that anything is wrong but SomeProperty will not be updated in the Database. Took me the best part of a day to find this one.
you have to get the job first then you could successfully update it, chk below snippet
var job = context.Jobs.Where(p => p.Id == id).FirstOrDefault();
//apply your changes
job.Title = "XXXX";
///....
context.SaveChanges();
My issue was that I was attaching after I updated the object, when in-fact, you have to attach BEFORE you update any properties
context.Table.Attach(object);
object.MyProperty = "new value";
context.Table.SaveChanges();

Categories