Web Forms :: How To Bind EntityFramework Objects With Controls
Jun 14, 2010with asp.net 4, is there any way that we can automatically bind web controls (textbox, listbox, check, etc), to EF4 Objects?
View 2 Replieswith asp.net 4, is there any way that we can automatically bind web controls (textbox, listbox, check, etc), to EF4 Objects?
View 2 RepliesWith ASP.Net 4, is there any way that we can bind web-form controls to entity framework objects?
<asp:TextBox ID="UserName" runat="server" BoundTo="UserName" BindingSource="..."></asp:TextBox>
so just like in MVC I can
form.UpdateModel(userObj),
form.DisplayModel(userObj)
I'm tyring to bind a list of Dictionary objects to ListView, but for some reason it returns me an error, ItemTeplate
[Code]....
Code Behind
[Code]....
error says
[Code]....
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") %>
I know how to bind a simple objects to a dropdown list. However I am having problems binding my objects which contains sub objects to the control.i.e. with simple object i just do ddl.DataValueField = "myproperty"
with my objects they contains sub objects which i want to bind. I have tried ddl.DataValueField = "sub-object.myproperty" which doesnt work.
i am calling an webservice where my webservice is returing an object( which contains data like
empid name
1 kiran
2 mannu
3 tom
WebApplication1.DBLayer.Employee objEMP = ab.GetJobInfo(); now my objEMP has this collection of data
empid name
1 kiran
2 mannu
3 tom
how can i convert this object into( datatable or LIst) and bind to gridview
My DataTable is programatically generated, and contains objects of type JobInstance in the cells.
[Code]....
When I bind this DataTable to an ASP GridView, it only displays the first column. But if I remove the "typeof(Job)" when creating the column (the line with // !!!), the GridView displays all the columns by showing the result of JobInstance.ToString() in the cells. However, I have no access to the underlying JobInstance object, only the string values that are being displayed.
I need access to the JobInstance object when displaying the GridView (for example in the OnRowDataBound), because I want to access the fields inside JobInstance for each cell to determine formatting options, and add other links in each cell.
I got a problem when getting some data out of my EntityFramework using Linq
Heres my code
[Code]....
Heres the ClientViewModel :
[Code]....
As you can se in the ClientViewModel the Users property is a List
But when trying to compile I get a error saying
Cannot implicitly convert type 'AdminMVC.Models.Clients_Username' to 'System.Collections.Generic.List<AdminMVC.Models.Clients_Username>'
I am having some issues with my base class inheritance. I am currently employing Table per Type Inheritance for the following tables:
Database:
Members Table
- Member ID (PK)
- First Name
- Last Name
- Email
- ...
Students Table
- Member ID (FK)
- Credits
- Notes
- ...
Instructors Table
- Member ID (FK)
- Biography
- Office Hours
- ...
My Entity Data Model defines "Member" as the base class for both Students and Instructors, since members can be both students as well as instructors simultaneously. The problem, however, occurs when I attempt to get a list of Members objects. Because the database contains members who are indeed students AND instructors, the following exception is thrown:
All objects in the EntitySet 'CountyCollegeEntities.BaseMembers' must have unique primary keys. However, an instance of type 'CountyCollege.NET.Administrator' and an instance of type 'CountyCollege.NET.Student' both have the same primary key value, 'EntitySet=BaseMembers;ID=10016'.
I am beginning to think that I made a mistake by building these classes to inherit from Member although it has been ideal up until this point. But before I start ripping up all my existing code to remove this inheritance, I thought I would see if anyone has any tricks that would make this work. Any advice as to either how I can get around this error or a more appropriate way to structure my classes would be very much appreciated.
Cannot seem to find a good fit for my question so I will ask here.
Does Asp.Net 4.0 solve the problems with using Views with EntityFramework is not able to recognize primary keys.
What I'm trying to do is rather basic, but I might have my facts mixed up. I have a details page that has a custom class as it's Model. The custom class uses 2 custom objects with yet another custom object a property of one of the 2. The details page outputs a fair amount of information, but allows the user to post a comment. When the user clicks the post button, the page gets posted to a Details action that looks something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Details(VideoDetailModel vidAndComment) { ....}
[Code]....
The only fields on the form that is posted are CommentText and VideoId. Here is what the VideoDetailModel looks like.
public class VideoDetailModel
{
public VideoDetailModel()
{
[Code]....
I suppose if I added more form fields for the properties I need, they would get posted, but I only need 1 form entry field for the CommentText. If I could get the same Model objects value that were sent to the page to post with the page, it looks like the solution is rather simple. I think using the RenderPartial in the middle of a form is problematic somehow to how the form gets written in html. I can't really put my finger on why things went bonkers, but if I do my RenderPartials before my form and then begin my form with the text entry field and the hidden VideoId, the default ModelBinder works just fine. I was beginning the form, writing the hidden VideoId, rendering several partial views, create my CommentText field, and then closed the form out. The CommentText field would get bound just fine. The hidden VideoId would not. Maybe I missed a rule somewhere about using RenderPartial.
For completeness, the partial view I was rendering took a Comment object and just wrote out it's CommentText data. Several of these objects would exist for a single Video object. All of this data was in a custom type and passed into the View (the main view) as it's Model. This partial view did not have a form and did not have any data entry fields.
I have Create and Edit forms for Categories. Columns are Id, CategoryName, Order, CreatedOn. On Create form I save the values for all but on Edit form I need to change only CategoryName. Below is the code. Problem is that on Edit form only CategoryName field exists which on submit button is passed to Edit Action. Whenever I update Order and CreatedOn becomes null because the values are not returned from form. Someone tell me any good approach how to Updated selected values in EF. Below is code.
Making multiple Get calls. Form is saving fine but I don't like the approach. Need clean approach. Anyone got better solution to thiis?
[Code]....
I am working on my first project with the Entity Framework and am having some difficulty displaying advanced information with the EntityDataSource and a ListView.
For example, given the two entities:
Item
Name
Price
Order
Number
Items <---- Navigation Property to Items contained in the Order
I want to display a list of all orders with a column with the total number of items in the order and a column with the sum of the prices of all items in the order.
I am using an EntityDataSource configured as follows:
<asp:EntityDataSource ID="eds" runat="server" ConnectionString="name=NDSEntities"
DefaultContainerName="NDSEntities" EnableFlattening="False" Include="Items"
EntitySetName="Orders"></asp:EntityDataSource>
In the ItemTemplate of the ListView, I can write the order number as follows:
<%# Eval("Number") %>
I had trouble figuring out how to display a count of items in the order. I tried using Items.Count() function in select statement in the EntityDataSource but that didn't work. Eventually I figured out I could do the following in my ItemTemplate:
<%# Eval("Items").Count() %>
Now I am stuck trying to get the sum of the items. I am stuck here. I have tried using
<%# Eval("Items").Sum(Function(i) i.Price)%>
but I get the following error:
Public member 'Sum' on type 'EntityCollection(Of Item)' not found.
This confuses me because I know that Sum is a method of EntityCollection(Of ).
My two questions are as follows:
Am I getting the item count correctly?
How should I go about getting the sum of the prices of the items?
Im tring to implement some generic logging in the entityframework 4.0 using the SavingChanges event in the entity context.
I want to record details about any create/ update and deleted records including the id of the record being changed (which is always an int identity field). During the update and delete processes I can get the id for the record using
Dim AddedItems = Statemanager.GetObjectStateEntries(EntityState.Added)
For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Added)
NewLogItem.RecordId = CInt(entry.EntityKey.EntityKeyValues(0).Value.ToString())
Next
But I obviously cannot get the id of the about to be inserted record during an insert becuase it hasn't been written to the database yet, is there a simple way around this?
firstly a static class only ever exists once and is not an instance. Any static members (ie static int NoOfPeople;) is stored in one place and is shared between all sessions (like the old global variables).
Now static methods is where i'm not 100% sure. If I have a static method that doesn't use any other static members could this cause inconstant results, example (this is a fairly pointless method but just a quick example of the top of my head)
[Code]....
So in this example if two sessions (or threads) were to call this at the same time - would they both get back the expected results, because the method only uses private data (a, b and totalToReturn).Im sure this sounds a little simple but I will be using static methods to build user objects and various other objects that there will have to be a 100% garentee that the objects will not get mixed up between sessions and the wrong things return to the user.
SaveChanges can generate an UpdateException when an object added to the ObjectContext cannot be successfully created in the data source. This can happen if a row with the foreign key specified by the relationship already exists. When this occurs, you cannot use Refresh to update the added object in the object context. Instead, reload the object with a value of OverwriteChanges for MergeOption.
In a table, a foreign key column can have a single value multiple times. e.g. DepartmentID foreign key in Users Table: More than one User can have same DepartmentID foreign key.
So how can this cause an UpdateException ?
I would like to call a method in the ObjectContext which returns EntityCollection and have it sorted the way I want by default. For example, Imagine I have the following Category table/class:
CategoryID (PK)
Name
ParentID (FK_Category) foreign key
pointing to CategoryID itself.
(This table is the base for a tree structure of Categories and SubCategories)
Now, in my data model, the public partial class Category : EntityObject has a property which returns all Categories that have ParentID==CategoryID, in other words, EntityCollection<Category> SubCategories.
Alright, now i want to show in my page all the Categories and SubCategories by using Repeater:
<asp:Repeater ID="rptSubCategories" runat="server">
<ItemTemplate>
<%# Eval("CategoryID") %> - <%# Eval("Name") %>
<asp:Repeater ID="rptSubCategoryCategories" runat="server" DataSource='<%#Eval("SubCategories")) %>'>
<ItemTemplate>
<%# Eval("CategoryID") %> - <%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Then in code behind, I set the DataSource:
IList<Category> categoryList = new CategoryProvider().GetAll();
rptSubCategories.DataSource = categoryList;
rptSubCategories.DataBind();
Simply and everything works! Except that, rptSubCategoryCategories doesn't gives sorted Categories by Name. The only way I found to do it, is to change its DataSource from:
DataSource='<%# Eval("SubCategories")) %>'
to:
DataSource='<%# ((EntityCollection<Category>)Eval("SubCategories")).OrderBy(p => p.Name) %>'
but I wish I could do something else to have a default sorting so i don't need to call the OrderBy. Something like Attributes like we do in DynamicData, following the tutorial at [URL] Setting the default sort column of an Entity with DisplayColumnAttribute. Unless somebody tells me it's impossible what I want to do.
Using .NET 4.0 BETA 2
I'm working on a project which is using EntityFramework 4 and I am using the entity objects as my business objects. I ran into an issue recently where I had a context declared in a using statement in a user control. The method the statement was in returned an entity object which got used in another control. So I had to detach the entity then attach it to the new context in the other control. I would like to avoid this if possible. What I'm thinking is I would like to declare a context in the master page and then pass that to any page/usercontrol that needs it so they are all using the same context and I don't have to write all these using statements.
My questions are these:
1) is it a bad practice to declare a context on Pre_Init/Page_Load and then dispose of it on Page_Unload?
2) if it is what is the best practice for handling them?
3) if I do go the route of declaring the context in the master page what is the best way to pass that to the pages/usercontrols?
I have not found any way to intercept or override calls to createquery in my datacontext. What I am trying to do is to allow for global filters, i.e. if a user has access to only a subset of entities I would like to filter away these on the lowest level possible. Is there a way to do this? I have tried several apporaches but no one worked out. Perhaps I lack patience or is just plain stupid, but I think it should be possible! So if anyone has any pointers to where
View 2 RepliesI have connected listview by using datasourceid that means by usingĀ "sqldatasource1" now i want to change value of listview at run time according to search so for that i am using datasource at codebehind. but it give an errorĀ
"listview have already bind with datasourceid you can not bind it with datasource"
what should i do for solving my requirement.
I have a List of Customers. Now I want to display these customers in a gridview and that is easy. I just set the datasource and use the databind method of the gridview. (I use template fields). But now I want to display FirstName and LastName of the customer as one column.I am aware of how to use the rowdatabound event to manipulate the gridviewrow's controls, but I am not sure how to gain access to the customer object within this method.So here is some code which of course not works.
protected void grdVirtualCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
System.Web.UI.WebControls.GridViewRow row = e.Row;
((Label) row.FindControl("lblName").).Text=Customer.FirstName + " " Customer.LastName;
}
I use a repeater on my website.My code for this example is
<ItemTemplate> Item: <%#DataBinder.Eval(Container.DataItem, "Col")%><br> </ItemTemplate>
I'm working on a project in which we have a database, data layer (entity framework), business layer and web/UI layer.I want to use ASP.NET Dynamic Data for the web layer, but don't want it to access the data layer or database, as I want it to be purely running off business logic, and not directly accessing the data.However, it appears that Dynamic Data only allows Linq-to-SQL or entity framework data sources to be used.Has anyone used it with business-layer objects instead?
View 1 RepliesI have my gridviews, buttons and labels put into tables:
[URL]
Here is how the page looks when I run it:
[URL]
Then when I select an Order this happens:
[URL]
Why is it when I select an Order and the second gridview pops up theat it moves my text and Ship button down? I thought I had it setup in the tables so this wouldnt happen?
I'm creating in my code a list of object which must be displayed later in a table.
In Winforms I'd simply bind the DataGridView to the list, and everything is fine.
However, when I try to set the GridView's data source to the list, nothing happens, and I can't find a way to do this with any of the procided data sources(Such as ObjectDataSource, etc.).