How To Update Entity Objects Without Deleting
Sep 20, 2010
I have an entity generated from my database that contains one table. When i make changes in the DB i obviously would like these changes to reflected in my model.
My current approach is to delete the item from the designer and then right-click - update model from database. This works for me at the moment. Is there a different approach to refreshing these entity tables ?
View 1 Replies
Similar Messages:
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
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
Apr 10, 2010
EF is so frustrating. I can't seem to be able to get my head around what I need to do so I can delete an object. I seem to be able to remove the object but not the related child objects. Can anyone tell me what is the rule of thumb when you want to delete all related child objects of a given object? I've tried loading all related objects like this:
Entry entry = ModelContext.GetObjectByKey(new EntityKey("ModelContainer.EntrySet", "Id", id)) as Entry;
entry.ChildEnteries.Load();
if (entry != null)
{
ModelContext.DeleteObject(entry);
ModelContext.SaveChanges();
}
I get errors related to the relationships: A relationship is being added or deleted from an AssociationSet 'EntryEntry'. With cardinality constraints, a corresponding 'Entry1' must also be added or deleted. Why can't I just load the object using modelcontext.GetObjectByKey and remove it along with its child objects? My other question is can I delete an object using Entity command like so? DELETE e from objectset as e where e.id = 1 I've tried few variations and all of them throw exceptions.
View 1 Replies
Jun 30, 2010
I have an EDM, it includes the entities extension and history. My goal is to use history to keep track of all the changes made to extension entity. For example, if extension with ID 223 has its property 'Name_Display' changed - I want the history entity to record this.
I'm using ASP.NET with VB.NET. Where in my code do I put the hook to say, "update the history entity" and what should that hook look like?
View 1 Replies
Jul 9, 2010
I have 3 tables User, role and UserInRole THe entity frame work made entities for User and Role and I have successfully made a join with the user and role entities using user.add(role); but I can't seem to get it to remove the link (I want to retain the user and role just remove their association).
using (ProviderEntities context = new ProviderEntities())
{
User u = context.User
.Where(n => n.ApplicationName == application)
.Where(n => n.Username == username).First();
Roles r = context.Roles
.Where(n => n.ApplicationName == application)
.Where(n => n.RoleName == roleName)
.First();
r.User.Remove(u);
context.SaveChanges();
}
The oposite worked when I did r.User.Add(u); but it wont let me now remove it after it been created. Driving me mad as I can't see where I have gone wrong.
View 1 Replies
Jun 30, 2010
Im new to MVC i need help in manipulating Entity Reference , i have a USER , USER Role and User Status tables in my database,my FormViewModel is as
[Code]....
[Code]....
it solves my problem , but i dnt find it appropriate to query Entities again for getting reference Entity Key
View 5 Replies
Mar 19, 2010
I have the following tables:
Campaigns (CampaignId, CampaignName, etc)
Urls(UrlId, CampaignId, UrlText)
I have a relationship setup between Campaigns table and Urls (FK_Url_Campaign) everything works fine when I try to add a new campaign but when I try to insert a new Url I get:
Entities in 'DatabaseEntity.Url' participate in the 'FK_Url_Campaign' relationship. 0 related 'Campaign' were found. 1 'Campaign' is expected.
This is my code:
// INSERT
public int Insert()
{
Url dbUrl = new Url();
dbUrl.CampaignId = (int)CampaignId;
dbUrl.Url1 = (string)Url;
context.AddToUrl(dbUrl);
context.SaveChanges();
return (int)dbUrl.UrlId;
}
Pretty much i want update/add new campaign and then I call Insert for Url. how would i go about doing this?
View 2 Replies
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
Feb 10, 2011
I am mapping a stored procedure to an entity by right clicking on the entity (in the .edmx) and selecting "Stored Procedure Mapping." This brings you to a Mapping Details - "Name of Entity" Window that allows you to select the insert, update, and delete stored procedures associated with the Entity. It also maps the stored procedure parameter to the Entity "Property" (Column).
I'm gettin an error "error 2042: Parameter Mapping specified is not valid." The cause of the error is fairly obvious, in the Insert stored procedure that has been selected, a 'CHAR' parameter is being mapped to an Int32 Entity Property. I altered the stored procedure parameter to match the entity, I deleted the stored procedure, readded, and reslected it as the Insert function. I also cleaned, validated, updated model from database. No matter what I do, the parameter list in the mapping details doesn't reflect the change to the stored procedure. It's stuck on a char --> int32 mapping, even though it has been changed, like it's buried deep in meta data some where.
View 2 Replies
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
Aug 5, 2010
I need to pass a list of Entity Objects from Controller to View but not put it in the Model context. It is the users homepage, but I am putting a list of alerts on the users home page(somewhat like facebook). So I need the User Context as the Model I pass but need to pass the Alert model as well so I can show the list of alerts.. How would I do that? The code below is what I have so far..
UserController
[Code]....
UserRepository
[Code]....
View 1 Replies
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
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
Sep 21, 2010
I'm writing a custom .NET MembershipProvider (not the built in one) and trying to update using Entity Framework. But of course i have no access to (Try)UpdateModel. How can i update it?
View 3 Replies
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
Dec 7, 2010
I am tring deleting the image in the gridview and in folder where it locate . My page in the update panel
write a funtion to delete in the delete button event , it not working in update panel when i comment the
update panel then it working properly.
View 2 Replies
May 29, 2010
I have and Article object that I update in my controller.... the object is passed into the controller and then I just call UpdateModel(inArticle) and it was all good. I now expanded my article to belong to a category and want to do that update there as well. I am not sure if it was the right thing to do but just as a start i hard-coded an update to the ArticleCategory table, just after I do the UpdateModel. This works but I am not sure how to code this update?
I am using the repository patter and i somehow feel that I should be passing an Article and an ArticleCategory object from the view to the controller? While I was writing this I thought that I could just extend my article object to include the categoryID but what if I really wanted to pass two un-related objects from the view to the controller? The UpdateModel persistes the database objects as by VoodooMagic, how would it work if I wanted to update 2 un-related objects?
View 3 Replies
Sep 14, 2010
I have been trying to design a form, which uses a view model that contains an object array. I want to set up this form so that when the submit button is clicked, all the members of the array are updated. Here is my code:
The class definition of the array element:
[Code]....
The problem is that when I clicked the submit button, none of the luSubject objects in the array Subjects got updated. But if I set up some initial values for the members of the luSubject objects, for instance, set the Name field to be "Maths" in the constructor of luSubject class, then it got displayed on the text box when the form page was loaded. This suggests that this form could display the data in the array, but cannot update it.
View 8 Replies
Jul 2, 2010
I found some code on the web and it threw me off. Look at the code below. You will notice only when the Hits == 1, does the cache get added. After that, the cache object isn't updated. It begs the question, does the object when updated, update the cache as well automatically? The answer here would make me remove some code in some of my classes.
public static bool IsValid( ActionTypeEnum actionType )
{
HttpContext context = HttpContext.Current;
if( context.Request.Browser.Crawler ) return false;
string key = actionType.ToString() + context.Request.UserHostAddress;
var hit = (HitInfo)(context.Cache[key] ?? new HitInfo());
if( hit.Hits > (int)actionType ) return false;
else hit.Hits ++;
if( hit.Hits == 1 )
context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
return true;
}
I would only guess that I would need to add the lines after the if statement:
if( hit.Hits == 1 )
context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
else if (hit.Hits > 1)
{context.Cache.Remove(key);
context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
}
Found the code at the bottom of the page here: http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx?msg=2809164
View 1 Replies
Feb 1, 2011
I've written some pages with ASP.net Repeater and GridView objects. I've seen that some other programmers write pages with these objects; but they make these objects do very nifty things.
For example, I've seen pages where a user clicks on a button and a jQuery dialog appears. When the user enters data into the dialog and clicks a button, the data is submitted using AJAX and the gridview/repeater is updated without reloading the page or posting back. What are good practices for accomplishing this?
View 2 Replies
Dec 1, 2010
I'm working on a school project where my website idea of choice is one that creates mixtapes (well, you'd download them or burn them from the site, but I need not implement that). The site allows its users to create 6 song mixtapes that are then published into a transaction table.
That part I am fine with. Making the selection page is tough. The way I have it set up is that there are 6 columns with 3 drop downs. First the user picks the genre, then the artist WITHIN the genre, and the song from the artist (GENRE > ARTIST > SONG). So, I would need the ARTIST drop-down list to populate once a SelectIndexChanged occured on GENRE. Same with SONG, but it would use ARTIST instead of genre.
Repeat that 5 more times and click a button, and it would create a table and post it to the database.
I have thought up of 2 ways to go about it.
1) Create a session that expires once the user clicks the "create" button. This would be sluggish, as there would be about 12 page refreshes, and 12 session variables I'd need to store.
2) AJAX/jQuery. This way would be awesome, but I have no idea how in the world to write jQuery in such a manner that on an event it calls a method from a code-behind file.
One thing I found out before my brain went to mush (I've been working on this for 6 hours now), is that one way people have done this is to call a non-related .aspx file that serves as a method. The idea is ok, but how do I go about getting it to update objects on the page the user is currently on? I'd believe there is a simpler way to do this, and am looking to you guys for some guidance on how to dynamically update dropdownlists.
View 2 Replies
Sep 27, 2010
I have a repeater which binds a set of data. Within this repeater is a column with various controls for updating, deleting, etc. These are image buttons which fire an onclick event such as "DeleteRecord". All this does is fire a stored procedure, passing in the ID of the record to delete from the CommandArgument of the object.
This works wonderfully... except for one rather huge problem. Once you delete a record, if you refresh the page, the record where the first deleted record used to be gets deleted. For instance... if I have 4 records
1 Record1
2 Record2
3 Record3
4 Record4
and I delete record 2... The page reloads with (which is fine):
1 Record1
3 Record3
4 Record4
...if I then hit refresh...
1 Record1
4 Record4
I assume this is because the erroneously deleted object (record3) is now in the same hierarchical place as the old object used to be and .net therefore doesn't know the difference, the page refreshes and fires the onlick event, grabbing out the command argument of the new object and deletes based on the ID as obtained from the commandargument of the new object. This is obviously a huge problem, if a client did this it would destroy data erroneously and I'm at a loss here. Is there any way to stop this from happening? I'm not sure if there is a better way to go about doing things or not. If there isn't, I need some sort of way to tell the page not to execute the event or to cross reference the ID of the object that is intended for deletion against the object itself...
Code below for convenience...
EDIT Wrapped a LinkButton around it because I have some jquery code in here as well which stops the page execution to wait for user confirmation. Pressing "ok" continues page execution.
<asp:LinkButton ID="oDeleteLink" CssClass="oDeleteIcon" CommandName="Delete" CommandArgument='<%# Eval("iAccountID") %>' runat="server">
<asp:ImageButton ImageUrl="/files/system/icons/trash-steel-16.png" ToolTip="Delete This Account" AlternateText="Delete" ID="oDeleteIcon" runat="server" />
</asp:LinkButton>
protected void oAccounts_ItemCommand(Object Sender, RepeaterCommandEventArgs e) {
if (e.CommandName == "Delete") {
int ID = e.CommandArgument.ToString().Numeric();
db.SPs.SpDeleteAccount(ID).Execute();
UI.Confirm(uiBroadcast, "Account has been deleted", "300px");
BindAccounts();
}
}
View 2 Replies
Dec 6, 2010
I am using EF4 with POCO entities and having problems to update an existing item. In a webbapp I have an ajax function fetching an entity object from the database through EF4. Then i make some changes to it and when I try to update the record in the database I call the Attach-method but it is not saved. I guess this has something do with that I am not in the same context anymore...so my question is how to make an update of a previously fetched record if the context which was used to fetch record is disposed?
View 3 Replies
Jan 14, 2010
I have following problem: in the Controller I call TryUpdateModel to send the changes made in the form back to the database. Then I save the entity, but no changes to database are made.
Here is the code from Controller:
[Code]....
Then the changes made to database. (ChangingSet have then also pending changes).
View 12 Replies