Entity Framework - Collection Of Complex Child Objects In MVC 3 Application?

Feb 20, 2011

I want to be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .

For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples.

[Code]....

This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox...

View 2 Replies


Similar Messages:

Use FormView In Order To Insert Complex Entity Framework Objects?

Jun 11, 2010

I'm trying to use formview in order to do insert of a new entity object (called Customer) Customer has a reference to another entity called Address. How can I fill both of them in the same formview?

View 1 Replies

C# - Best Way To Edit And Update Complex Viewmodel Objects Using Mvc2 And Entity Framework?

Apr 2, 2010

I have a table in my database with a one to many relationship to another table, which has a relationship to a third table:

[Code].....

This seems to work fine. My question to you good folks: Is there a correct way to do this? I tried following the making a custom model binder per the blog link I posted above but it didn't work (there was an issue with reflection, the code expected certain properties to exist) and I needed to get something going ASAP. PS - I tried to cleanup the code to hide specific information, so beware I may have hosed something up.

View 1 Replies

ADO.NET :: How To Use Procedure Return Complex Type In Entity Framework

Feb 18, 2011

If I have Database Stored Procedure retrun Complex type (Contain from Columns for 2 tables) ( Composite) and No Relation between them so i can't use Navigation Property ... so how can I use That in ADO.NET Framework specially when i try to use Add Function Import i didn't find any thing else None, Scalars, Entites.

View 1 Replies

ADO.NET :: Gen Objects Mapped To Entity Framework?

Dec 6, 2010

I've been tasked to convert our old DAL that have gen objects to possibly the Entity Framework 4.0. We create objects inheriting from our genned objects and have a ton methods our legacy codes uses. Does anyone have an idea or possible solution on how to create an entity framework model that maps to our old genned objects? Or a solution that requires us to modify our legacy code minimally?

View 1 Replies

Entity Framework Getting Objects Not Immediately Related?

Jun 24, 2010

I am using Entity Framework for my .NET application. I have been able to return objects and their directly-related objects as well (very convenient), but I am having trouble getting the objects of those objects.

IEnumerable<Lot> i = (((ObjectSet<Car>)_carRepository.GetQuery()) .Include(a => a.CarTypes).Take(10).ToList()

This works and I can access carTypes, however I cannot figure out how to access tables associated with CarTypes (e.g. tables which have fields associated with the car types). I tried to use a Join however I was unable to figure out how to get it to work right.

View 2 Replies

Can A Entity Framework Trackable Collection Be Bound To A Gridview

Mar 28, 2011

I've got a GridView on a ASP.Net page. I would like to set the DataSource of the Gridview to a trackable collection of Entity Framework objects. I though the code should look like this:

this.gvMyGridView.DataSource = entity.MyDetailedItems;
this.gvMyGridView.DataBind();

But this doesn't display any data.

I am using self tracking entities and the MyDetailedItems is a navigation property to rows from another table.

View 2 Replies

Adding To EntityCollection Adds To The End Of Collection In Entity Framework?

Feb 28, 2011

I'm trying to have a View where the user can add items in a collection without having to go to a new View (the scenario is a sort of CV site where the user adds info about work experience, skills, etc, and it would seem absurd to go to a new View to add each little thing).

So I have an edit View that shows a number of text boxes for the already added items, and there's an ajax call to go to a method to fetch the collection fresh if the user adds an item.

Here are the methods in question:

[code]....

View 1 Replies

ADO.NET :: Finding Lambda Expression Against Entity Framework Collection?

Aug 6, 2010

I'm new to LINQ and EF and I seem to be having trouble working this out.

I have a many-to-many relationship between my Location and Region tables. When adding or editing a Location, my interface allows the user to check any number of related Regions. If they click OK, I need to add any new relationships that were checked, and delete any existing relationships that have been unchecked. My basic code is shown below.

However, this code doesn't work. Lower down, the line location.Regions.Contains(region) returns false even when the location already is related to the region. The issue appears to be because the region is from my populated listbox that was initialized earlier and is no longer part of the current EF context. But if I try and add it, I get an error that there is already a Region with that ID.

It seems like what I want to do is change this line to something like location.Regions.Contains((r) => r.RgnID == region.RgnID) so I'm only testing for a particular ID. But this gives me the error "Cannot convert lambda expression to type 'TrailCalendar.Region' because it is not a delegate type."

I don't understand this error but, either way, I'm not sure how I can test if the relationship already exists without reloading a bunch of data, which I'd like to avoid.

View 1 Replies

Ms Entity Framework Delete Child Object

Mar 10, 2010

i have 2 tables without any cascade deletind. i wont to delete parent object with all child objects. i do like this

//get parent object
return _dataContext.Menu.Include("ChildMenu").Include("ParentMenu").Include("Pictures").FirstOrDefault(m => m.MenuId == id);
//then i loop all child objects
var picList = (List<Picture>)menu.Pictures.ToList();
//foreach (var item in menu.Pictures)
for (int i = 0; i < picList.Count; i++)
{
if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ImgPath)))
{
File.Delete(HttpContext.Current.Server.MapPath(picList[i].ImgPath));
}
if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ThumbPath)))
{
File.Delete(HttpContext.Current.Server.MapPath(picList[i].ThumbPath));
}
//**what must i do here?**
//menu.Pictures.Remove(picList[i]);
// DataManager dm = new DataManager();
// dm.Picture.Delete(picList[i].Id);
//menu.Pictures.de
//_dataContext.SaveChanges();
//picList[i] = null;
}
//delete parent object
_dataContext.DeleteObject(_dataContext.Menu.Include("ChildMenu").Include("ParentMenu").Include("Pictures").FirstOrDefault(m => m.MenuId == id););
_dataContext.SaveChanges();

View 1 Replies

Entity Framework. Updating EntityCollection Using Disconnected Objects Via Navigation Property?

Apr 22, 2010

I have a question, much liket this unanswered one. I'm trying to work with the entity framework, and having a tough time getting my foreign tables to update. I have something basically like this in the DB:

Incident (table):

-ID
-other fields

Responses (table):

-FK:Incident.ID
-other fields

And and entities that match:

Incident (entity)
-ID
-Other fields
-Responses (EntityCollection of Responses via navigation property)

Each Incident can have 0 or more responses.

In my Webpage, I have a form to allow the user to enter all the details of an Incident, including a list of responses. I can add everything to the database when a new Incident is created, however I'm having difficulty with editing the Incident.

When the page loads for edit, I populate the form and then store the responses in the viewstate. When the user changes the list of responses (adds one, deletes one or edits one). I store this back into the viewstate. Then when the user clicks the save button, I'd like to save the changes to the Incident and the Responses back to the DB. I cannot figure out how to get the responses from the detached viewstate into the Incident object so that they can be updated together.

Currently when the user clicks save, I'm getting the Incident to edit from the db, making changes to the Incident's fields and then saving it back to the DB. However I can't figure out how to have the detached list of responses from the viewstate attach to the Incident. I have tried the following without success:

Clearning the Incident.Responses collection and adding the ones from the viewstate back in:

Incident.Responses.Clear()
for each objResponse in Viewstate("Responses")
Incident.Responses.add(objResponse)
next
Creating an EntityCollection from my list and then assiging that to the Incident.Responses
Incident.Responses = EntityCollectionFromViewstateList
Iterating through the responses in Incident.Response and assigning the corresponding object from viewstate:
for each ObjResponse in Incident.Responses
objResponse = objCorrespondingModifedResonseFromViewState
Next

These all fail, I'd like to be able to merge the changes into the Inicdent object so that when the BLL calls SaveChanges on the changes to both the Incident and Responses will happen at the same time.

View 1 Replies

Entity Framework 4 - Check If Navigation Property Collection Is Empty, Without Include() Or Load()?

Sep 28, 2010

In an MVC view, I'm looking for a way to determine if a parent entity's collection of child entities is empty, so I can decide if I need to call a RenderPartial() or not.

For a one-to-one I've been using the following:

<% if (Model.Book.GenreReference.EntityKey != null) %>
{.....}

but I'm unsure how to do it in a one-to-many scenario, or if it can even be done without the use of Include() or Load().

View 2 Replies

Pattern For Retrieving Complex Object Graphs With Repository Pattern With Entity Framework

Oct 13, 2010

We have an ASP.NET MVC site that uses Entity Framework abstractions with Repository and UnitOfWork patterns. What I'm wondering is how others have implemented navigation of complex object graphs with these patterns. Let me give an example from one of our controllers:

[code]....

It's a registration process and pretty much everything hangs off the POCO class Person. In this case we're caching the person through the registration process. I've now started implementing the latter part of the registration process which requires access to data deeper in the object graph. Specifically DPA data which hangs off Legal inside Country.

The code above is just mapping out the model information into a simpler format for the ViewModel. My question is do you consider this fairly deep navigation of the graph good practice or would you abstract out the retrieval of the objects further down the graph into repositories?

View 2 Replies

DataSource Controls :: Entity Framework - Parent And Child Relationships?

Feb 4, 2010

I am just getting started with entity framework with asp.net 3.5 using VS 2008

There are two tables, Categories & Subcategories:

Category table: CID, CategoryName Sub Category table: SID, CID, SubCategoryName I would like to get SID, CID, CategoryName, SubCategoryName in the gridview. Just as we write a select statement i.eSelect a.sid, b.cid, b.categoryname, b.subcategoryname from subcategories a inner join categories b on a.cid=b.cid & put the same in a gridview.

I was trying for the whole day & couldnt get atleast one url that would teach how to do it.

View 3 Replies

Update Model Child Collection In MVC 3 Application?

Feb 25, 2011

This is part of a larger problem which has plagued me for a while now (see "EntityCollection already initialized" error with entity as model in Asp.Net MVC? for the entire picture).

But I found a web site with someone who had faced a similar problem and apparently solved it for his needs [URL]. I tried it, but had to make some modifications to fit my code, and the helper methods supplied by a tutorial by Steven Sanderson (see previous post).

I'm very close it seems, but not quite:

UpdateModel(consultant, "Consultant");
if (vm.Programs != null) //Unnecessary? Can it even be null if it's initialized from the model?
for (int i = 0; i < vm.Programs.Count; i++)
{
Program formProgram = vm.Programs[i];
Program modelProgram = consultant.Programs.SingleOrDefault(x => x.Id == formProgram.Id);
if (modelProgram == null)
_repository.AddProgram(formProgram);
else
modelProgram = formProgram;
UpdateModel(modelProgram); //Doesn't work. The modelProgram object does get updated with the correct property values, but it isn't saved to the repository...
}
_repository.Save();

Although this follows the example on the site above, and the modelProgram does get updated with the changed properties, these values are not saved to the database on _repository.Save() on the Consultant object, even though the modelProgram object is a reference to a Program object on the Consultant... What am I doing wrong?

I am using the Entity Framework by the way, if it isn't clear.

(BTW, if anyone has any input on the previous question and the whole picture, that would be welcome too, it is still unresolved).

UPDATE: There was apparently a mistake in here: UpdateModel didn't actually do any updating, I had just referenced a different object (the one in the viewmodel) for the modelProgram, so of course it had the right property values. I still want ideas for how to achieve this though...

View 1 Replies

Forms Data Controls :: Binding A Repeater To A List Of Objects That Have Child Objects?

Nov 17, 2010

have some Objects, lets say Employee and Role defined as below and I have defined relationships in my database that gives me a list of objects say employees and thanks to my framework each employee object also has a Role object linked via the RoleIDID, UserName, Password, Email, RoleIDRoleID, RoleNameSo in code I can do something like this

Employee emp = dataService_GetEmployeeByID(1);
string RoleName = emp.Role.RoleName;

Now here is my problemI can bind any object in a repeater and it works fine for the first level in my relationship

For instance <%# Eval("UserName") %>

But I need to be able to show the details for my child objects as well (Role) so something like this (which does not work)

<%# Eval("Role.RoleName") %>

View 2 Replies

Error CS0012 In Entity Framework And MVC Application.?

Jul 10, 2010

I've just created a new MVC 2 application that references both an entity model library and a services library, and all compiles fine without running the app, but when I try running it, I get the following runtime error"

Compiler Error Message: CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I have double checked umteen times (e.g. Umpteen*n) and the cited assembly is refenced in all three projects. If it wasn't, WTF would I not get a build error?

View 1 Replies

Exporting Entity Framework 4 Data Model To Entity Framework 3.5?

Oct 25, 2010

Is there a way to export a EF 4.0 Data Model to EF 3.5?

I looked around and found that we are not able to access EF 4.0 from a ASP.Net 3.5 project here: [URL]

Our project is the 1st to go to .Net 4.0 using Entity Framework and we (the team) were wondering if there was a way for the other projects that "might" need to access our data that are still using the .Net 3.5 framework.

View 1 Replies

Configure Entity Framework Metadata Locations For A Web Application?

Sep 9, 2010

I am trying to configure Entity Framework 4 in the Web.config file using this ConnectionString

[code]....

I would like remove the "*" and add the actual path for my dll file.

How to find the path for a dll in Visual Studio with no add-on? (I am pretty new in .net)

View 2 Replies

What's Mvc Model In Software Application Development And Entity Framework

Apr 2, 2010

Generally what is m.v.c model in software application development and entity framework in asp.net and are these diffrent form 3 layer d architecture(UI layer, Business access layer, Data access layer)

View 2 Replies

MVC 3 Application Using Ninject, Entity Framework 4 Code-First CTP 5, Patterns

Jan 24, 2011

ive tried to build some base project with above technologies. I wanted maximum flexibility and testability so i tried to use patterns along the way to make this as a base for future projects. However, it seem.something is wrong or whatever and i really need help here. So

i have two questions :1- Is there anything wrong with my current code ? Ive applied patterns correctly ?

2- Why do this code actually connect to the database, create it, but doesnt support insert even if i perform the corrects operation ? (Look at the end of the post for details about this error)

I have two entities : Comment and Review

COMMENT [Code]....

REVIEW[Code].... I built up a base repository for each of them this way :GENERIC REPOSITORY[Code]...For specific operations, i use an interface :[Code]....So i am getting the generics operations from the abstract class plus the specific operations :[Code]....As you figured out, i also use a database factory will produce the database context :DATABASE FACTORY [Code]....DISPOSABLE (Some extensions methods...)[Code]....DATABASE [Code]....And to finish, i have my unit of work....UNIT OF WORK[Code]....I also binded using Ninject the interfaces :NINJECT CONTROLLER FACTORY [Code]....however, when i call in the constructor ...[Code]....

This seem to create the database but doesnt't insert anything in the database in EF4. It seem that i may figured out the problem.. while looking at the database object.. the connection state is closed and server version throw an exception of this kind :

ServerVersion = '(((System.Data.Entity.DbContext (_database)).Database.Connection).ServerVersion' threw an exception of type 'System.InvalidOperationException'

I am doing the right things ? Is there anything wrong in what ive built ? Also if you have recommandation about the code i posted, i would be glad. I am just trying to the learn the right way for building any kind of application in MVC 3. I want a good a start.

I use :
- Entity Framework 4 Code-First CTP 5
- ASP.NET MVC 3
- Ninject as DI Container

View 4 Replies

DataSource Controls :: Entity Framework And Architecture Of Model - Create Application Using EF

Feb 10, 2010

I can't to understand clearly how to create strong and quickly application using EF. For example, I have class ForumPost (table ForumPost) for select one of record I write method like:

public ForumPost ForumPost(int ForumPostID)
{
return
(from i in _dataContext.ForumPostSet
where i.ForumPostID == ForumPostID select i).First();
}

all works. But on page (I use ASP.NET MVC) I should display info from another linked tables, ForumName (each post have ForumID) etc. So, I modify this method to:

public ForumPost ForumPost(int ForumPostID)
{
return
(from i in _dataContext.ForumPostSet
.Include("ChildPosts").Include("ParentPost").Include("Users").Include("Forums").Include("Tags").Include("ForumPostPolls")
where i.ForumPostID == ForumPostID select i).First();
}

ok, all works. Then I want to make some actions in model with ForumPost, i.e.

public void RootPost(int PostID, ref Models.ForumPost Root)
{
ForumPost post = ForumPost(PostID);
if (post.RootPost != null)
{
Root = ForumPost(post.RootPost.ForumPostID);
}
else
Root = post;
}

it works too. But problem is in speed. I not need in RootPost all those includes. So, I should to create one more method like:

private ForumPost ForumPostIncludes1(int ForumPostID)
{
return
(from i in _dataContext.ForumPostSet
.Include("ChildPosts")
where i.ForumPostID == ForumPostID
select i).First();
}

then ForumPostIncludes2, ForumPostIncludes3 etc... second way - redesign RootPost with LINQ expr, not with call another method. But in this way difficulties to change DB. third way? How to do it correctly?

View 1 Replies

MVC :: Using Data From Multiple Entity Framework4 Model Entity Objects In MVC2 Controller?

Sep 29, 2010

getting data from multiple Entities models into an MVC controller. Most of the examples I have seen for using EF in an MVC2 app only use a single entitiy.

I have just started using MVC2 in C# using the Entity Framework models (CIOps.model) created from an SQL database. I can create the controller and views using single tables of the model in MVC2, but I just cannot get my head around how to get data from multiple entity tables into the controller (similar to joins in T-SQL). I have included an example below of the controller code that works with a single entity table, tbl_tours (tbl_tour in DB).

Could someone please illustrate how this code would be changed to include additional columns from FK tables in addition to tbl_tours columns. E.g. the clients name from the tbl_clients, the coordinators name from the tbl_employees, and costs from tbl_costs entities? Is it possible to do this directly using the EF model entities/classes that are already created and not use LINQ, POCO, Repositories, etc.? The FK relationships are already in the EF models. I have included the whole controller code, but I just need a few examples of how to join the multiple entities, not rewrite every CRUD function function in the controller. I think this will get me over the hump in using EF in an MVC2 App. Also ignore the fact I am using the home controller, this will change in the application.

[Code]....

View 21 Replies

Passing Complex Objects To Javascript Via IScriptControl?

Mar 24, 2010

I'm playing around with a asp.net page that's using the IScriptControl interface to pass data from the code-behind to the custom javascript object running on the browser.I'm passing a number of properties via IScriptControl.GetScriptDescriptors(), and they're all working fine, except for one.That one is a class derived from System.Collections.Generic.Dictionary<>. And even that one has been working for me, so long as the elements in the collection were scalars - ints, doubles, and strings. But when I tried to pass a member of a class, it showed up as a null object in the javascript. The class in question is marked [Serializable]. I changed it to a struct, and got the same behavior.It looks as if the serializer used in IScriptControl does a shallow copy.

View 2 Replies

C# - ModelBinder With Multiple Selection And Complex Objects?

Feb 22, 2010

I'm trying to bind the selections in a multiple selection SELECT, to an IList input in the controller.

<select name="users" multiple="multiple">
<option>John</option>
<option>Mary</option>

[code]...

View 2 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved