How can I get data from only one table in relational tables in entity framework?
I had created two tables. One is Classes and other is Students, and classes has one-to-many students relationship, but when I try to get data, it returns data from students and from classes tables.
(System.Data.Entity.DynamicProxies.Class_A4175BA8B7189ED27663CF9F9601DDF445EED57DA923B995D31056ABB560F13A).
How can I remove this columnn?
Code:
TestDbEntities entities = new TestDbEntities();
dataGridView1.DataSource = entities.Students.ToList();
Not familiar with entity framework but the object you have listed there is a proxy object
System.Data.Entity.DynamicProxies.Class_A4175BA8B7189ED27663CF9F9601DDF445EED57DA923B995D31056ABB560F13A
That's why it has that strange name. If you trace your database call I would think that the query is not joining to the class table. Instead the proxy is generated to enable lazy loading. So if you never touch the class object, it is never grabbed from the DB.
Related
I have some data from an XML file that I have transposed and I can map to my Entities. So now I want to save them all to the database .
I was reading on SO Can Entity Framework add many related entities with single SaveChanges()?
The accepted answer does not have too much info but this statement:
'You don`t need to save changes every time if you use objects
references to newly created objects not IDs:'
My entities are derived from a dataset tables which all have a related Id columns.
And I guessing the answer is more or less that the related entity was created with something like this : item.SubItem = new SubItem();
rather than item.SubId = SubItem.Id;
So should I traverse my data tables and translate my dataset tables into Entities by creating the objects from the tables and adding them to the context.
So for each row in dt['Items'] if row has a subitem new SubItem {all values except the Id}..??
Any example code would be appreciated.
So after working to resolve the issue I discovered if I create a new object of my entity and map values to it excluding the ID column I can then assign this object back to the parent.
pseudo code is below:
myobject = new myobject(){ param1 = oldobject.param1}
myentityParent.ChildTableEntity.Add(myobject);
Here's my question. I have 2 models (Person, Event) and with EF and modelbuilder I generate a booking table (with IdPerson and IdEvent as properties).
So in my DB it's correct, I have 3 tables (Person, Event and Booking) with many to many relationship. But I have only 2 models in Visual Studio (Booking doesn't exist because of the self-generated table).
With my Controller I want to write an action for the Person to suscribe to an event and I have to write on my table Booking on the DB but it doesn't exist as a model so I can't do that .
How should I proceede?
Should I create a Booking model and delete my modelbuilder?
When you are using ORMs like EF, you can sit back and let the ORM manage these middle tables.
You can use
person.Events.Add(event)
or
event.People.Add(event)
and EF handles all and inserts a row with personId and eventId in that table.
Here you can find a complete sample:
http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-ef-4-1-building-many-to-many-relationship.aspx
I assume this is a model first approach.
The reason for having only 2 objects is that, by default, EF does not create objects for joint tables. What it does create is Navigation Property (Entity Framework - Navigation Property Basics). In one-to-many scenario, a navigation property inside a parent object contains a collection of entities in a foreign / child table. In many-to-many scenario, navigation properties of each entities will simply contain collections of its other entities.
(Using: Visual Studio 2010, SQL Server 2012, Entity Framework 4.0, MVC3 web application)
I have tables with one-to-many and many-to-many relationships, I used (database first) to automatically generate model classes, meaning I have objects inherited from EntityObject and the base class inherited from ObjectContext.
I am having trouble with (inserting, updating, deleting) objects.
For example when creating an object: I have a many-to-many relationship between 2 tables (Area and Cell) and the middle table (CellArea), and I want to add a new Cell object which is connected to many areas, so I did the following code:
Cell _cell = new Cell()
foreach (Area ar in current_areas)
{
var ca = new CellArea();
//ca attributes
_cell.CellAreas.Add(ca);
}
db.SaveChanges();
db.Cells.AddObject(_cell);
db.SaveChanges();
I tried other code snippets and none of them worked, I always get IEntityChangeTracker and other similar exceptions.
What is the proper way to manage such cases?
When there are intertable relationships EF should create what is known as navigational properties. When you perform the initial query you can either choose to have those properties loaded or not. In particular EF has a keyword named Include that allows you to populate those other properties at will. If all the other date is included and any changes are made, you only have to call the SaveChanges method and the original table data and all navigational property data is saved in one shot.
Google "EF Include"
I am using entity framework, code first, 4.0, hitting an existing legacy database for read-only access. The database is normalized, so
Table [Event]
[ID]
[Date_Entered]
[Event_Status_Key]
Table [Event_Status]
[Event_Status_Key]
[Event_Status_Description]
My class looks like
public class Event
{
public DateTime DateEntered { get; set; }
public string StatusDescription { get; set; }
}
This is a WCF service layer application.
My two questions:
Is there any easy way to populate the status description without creating a second Dictionary-type object? I've seen questions like this: Entity Framework Mapping to Lookup table, but they seem to be focused on object to object, and I really just want a primitive. I'd prefer using the fluent API as opposed to attributes.
When the data is loaded, is any of the data cached at the code layer? Or does each check on the StatusDescription mean a separate call on the [Event_Status] table?
Edit: A possible (more subjective, which is why I didn't bring it up) third question is how close should the data entities match the database. Is it always a one-to-one field/table? Is what I'm doing (joining two tables into one data entity obejct) bad?
Thanks.
Entity framework expects that you will map both tables as separate entities and use projection in your query:
var query = from e in context.Events
select new WcfEvent // Your original Event class is just DTO
{
DateEntered = e.DateEntered,
StatusDescription = e.EventStatus.EventStatusDescription
};
This example expects correctly one-to-one mapping of your Event and Event_Status tables.
If you need any kind of caching you will have to implement it yourselves. Projected results are not even tracked by the context.
I am stuck here.
Is it possible to map data from 2 different tables to 1 entity in Entity Framework 4.
I have a bunch of employees in one table, and in the other I have som project information.
I would like to combine these 2 tables in one Entity, and keep the tracking features etc., is that possible?
I do not want to use a function import, but do it solely through the Entity Model.
Can anyone help - when I try to do it, i get the following error all the time:
Error 3024: Problem in mapping fragments starting at line 2354:Must specify mapping for all key properties (MyProjectTable.PSInitials, MyProjectTable.ProjectID) of the EntitySet MyProjectTable.
Both key are mapped to their respective tables.
The new Entity are made with MyProjectTable as the basetable.
The relation between the 2 tables is a 1-*
Hope you can help.
/Christian
You cannot map two tables with a one-to-many relationship to one entity. If you don't want projecting the results into one object in code, consider creating a view and mapping it instead.
According to http://msdn.microsoft.com/en-us/library/bb896233.aspx
You should only map an entity type to
multiple tables if the following
conditions are true:
The tables to which you are mapping share a common key.
The entity type that is being mapped has entries in each
underlying table. In other words,
the entity type represents data
that has a one-to-one correspondence between the two
tables; the entity type represents an
inner join of the two tables.
The reasons for doing this are quite straightforward - for example, a table of data points that all have one of five 'types'. Obviously the 'type' will be a separate table for the sake of normalisation, but from an application point of view (working with the data) it makes more sense to have all properties in a single entity.
So we can't do this with Entity Framework - a supposed Object-Relational-Mapper. What, then, is the point of using such a framework?