Search Results

Search found 284 results on 12 pages for 'savechanges'.

Page 7/12 | < Previous Page | 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Linq2Entities: Update relationship?

    - by Poku
    Hey, How do i create a new row in a table which have a relationship with another table? I have an Employees table and a EmployeeProjects table. One Employee can have 1-* EmployeeProjects. Now i want to create a new EmployeeProject which relates to an Employee. How do i do this? Here is want i have tried so far: var ep = new EmployeeProjects(); ep.JobNo = jobNo; employee.EmployeeProjects.Add(ep); var originalEmployee = GetEmployee(employee.Id); _entities.ApplyPropertyChanges(originalEmployee.EntityKey.EntitySetName, employee); _entities.SaveChanges();

    Read the article

  • save changes problem

    - by ognjenb
    // GET: /Transporter/Edit/5 public ActionResult Edit(int id) { var FilesQueryEdit = (from i in FilesEntities.transporter where i.Id == id select i).First(); return View(FilesQueryEdit); } // // POST: /Transporter/Edit/5 [HttpPost] public ActionResult Edit(int id, transporter trn) { try { // TODO: Add update logic here FilesEntities.AddTotransporter(trn); FilesEntities.SaveChanges(); return RedirectToAction("Transporters"); } catch { return View(); } } This code inserts new row after post edited data. How to modify post action result to save changes in edited row without inserting new row

    Read the article

  • Why do a small amount of add/deletes take several seconds in EF4?

    - by TomWij
    Using the Entity Framework 4. I have created a Code First database in the past and a piece of code needs to delete and add 16 objects, this takes 6 seconds each. That's 300+ ms for each query! The deletes/adds occur in a foreach scope and there is a SaveChanges() outside the foreach. In the above image you see that each takes 6 seconds, which is 34% of the time, for 16 calls. That doesn't sound normal to me... Why is this and how can I improve the performance? If there is no solution: Are there any workarounds I can use? It would be a pain to rewrite my project...

    Read the article

  • Insert record into mysql db with Entity Framework

    - by sanfra1983
    Hi, the problem is that it will insert a new record in a mysql table, I have already done the mapping of the mysql db and I have already done tests returning data and everything works. Now I read from a file, where there are queries written, I have them run me back and the result of true or false based on the final outcome of single query written to the file. Txt; I did this: using (var w = new demotestEntities ()) ( foreach (var l listaqueri) ( var p = we.CreateQuery <category> (l); we.SaveChanges (); result = true; ) ) but it does not work, I sense that it returns no errors, but neither the result given written in the query. txt file is as follows: INSERT INTO category (id, name) VALUES (null, 'test2') anyone can help me?

    Read the article

  • Entity update from ASP.NET MVC page with post to Edit action

    - by mare
    I have a form that posts back to /Edit/ and my action in controller looks like this: // // POST: /Client/Edit [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Client client) My form includes a subset of Client entity properties and I also include a hidden field that holds an ID of the client. The client entity itself is provided via the GET Edit action. Now I want to do entity update but so far I've only been trying without first loading the entity from the DB. Because the client object that comes in POST Edit has everything it needs. I want to update just those properties on the entity in datastore. So far I've tried with Context.Refresh() and AttachTo() but with no success - I'm getting all sorts of exceptions. I inspected the entity object as it comes from the web form and it looks fine (it does have an ID and entered data) mapped just fine. If I do it with Context.SaveChanges() then it just inserts new row..

    Read the article

  • How to modify posted form data within controller action before sending to view?

    - by Gary
    I want to render the same view after a successful action (rather than use RedirectToAction), but I need to modify the model data that is rendered to that view. The following is a contrived example that demonstrates two methods that that do not work: [AcceptVerbs("POST")] public ActionResult EditProduct(int id, [Bind(Include="UnitPrice, ProductName")]Product product) { NORTHWNDEntities entities = new NORTHWNDEntities(); if (ModelState.IsValid) { var dbProduct = entities.ProductSet.First(p => p.ProductID == id); dbProduct.ProductName = product.ProductName; dbProduct.UnitPrice = product.UnitPrice; entities.SaveChanges(); } /* Neither of these work */ product.ProductName = "This has no effect"; ViewData["ProductName"] = "This has no effect either"; return View(product); } Does anyone know what the correct method is for accomplishing this?

    Read the article

  • PHP Global variable in class is reset

    - by Robert
    I have a web form that manipulates records in a MySQL database. I have a method for displaying an edit interface for both creating new records and editing them if ($_POST['new_page']) { print "<h2>Create new page</h2>\n"; $isNew=1; $this->EditForm(); } else if($_POST['edit']){ print "<h2>Edit page</h2>\n"; $isNew=0; $this->EditForm(); } I am trying to use the global variable $isNew to determine where a record is to be added or updated. However, whenever my SaveChanges() function is run, $isNew is always 0. $isNew is declared immediately after the class declaration, outside all of the functions. class Editor{ public $isNew;

    Read the article

  • Automatically update audit information on Entity

    - by Nix
    I have an entity model that has audit information on every table (50+ tables) CreateDate CreateUser UpdateDate UpdateUser Currently we are programatically updating audit information. Ex: if(changed){ entity.UpdatedOn = DateTime.Now; entity.UpdatedBy = Environment.UserName; context.SaveChanges(); } But I am looking for a more automated solution. During save changes, if an entity is created/updated I would like to automatically update these fields before sending them to the database for storage. Any suggestion on how i could do this? Let me know if any more information is needed.

    Read the article

  • How to create relationship mapping via Entity framework

    - by James
    I have following domain model: User { int Id; } City { int Id; } UserCity { int UserId, int CityId, dateTime StartDate } In the function where I have to attach a user to a city, the following code is working for me: UserCity uc = new UserCity(); //This is a db hit uc.User = MyEntityFrameworkDBContext.User.FirstOrDefault(u => u.ID == currentUserId); //this is a db hit uc.City = MyEntityFrameworkDBContext.City.FirstOrDefault(c => c.ID == currentCityId); uc.StartDate = userCityStartDate; //this is a db hit MyEntityFrameworkDBContext.SaveChanges(); Is there any way I can create relationships with just one single DB hit? The first two db hits are not required, actually.

    Read the article

  • Navigation properties not set when using ADO.NET Mocking Context Generator

    - by olenak
    I am using ADO.NET Mocking Context Generator plugin for my Entity Framework model. I have not started on using mocks yet, just trying to fix generated entity and context classes to make application run as before without exceptions. I've already fixed T4 template to support SaveChanges method. Now I've got another problem: when I try to access any navigation property it is set to null. All the primitive fields inherited from DB table are set and correct. So what I am doing is the following using (var context = MyContext()) { var order = context.Orders.Where(p => p.Id == 7); var product = order.Products; } in this case product is set to null. But that was not a case while using default code generator, it used to return real product object. Thanks ahead for any suggestions!

    Read the article

  • delete data using entity framework

    - by user3474542
    The objective of the method below is to delete the data from the database using entity framework. I am populating the subscriptions entity by passing two parameters and then calling the atttach and remove method of the context class. Bureau entities is the context class. using (BUREAUEntities bureauEntities = new BUREAUEntities()) { var subscription = new SubcriptionRepository().GetSusbcriptionBySubscriptionTypeId(subscriptionTypeId, companyId); bureauEntities.Subscriptions.Attach((DataAccessLayer.DatabaseModel.Subscription)subscription); bureauEntities.Subscriptions.Remove(subscription); bureauEntities.SaveChanges(); } I am getting the following error message at An entity object cannot be referenced by multiple instances of IEntityChangeTracker at line bureauEntities.Subscriptions.Attach((DataAccessLayer.DatabaseModel.Subscription)subscription); Could somebody tell me where am I going wrong ?

    Read the article

  • Linq To Sql Entity Updated from Trigger

    - by James Helms
    I have a Table called Address. I have a Trigger for insert on that table that does some spacial calculations on the address that determines what neighborhood boundaries it is in. address = new Address { Street = this.Street, City = this.City, State = this.State, ZipCode = this.ZipCode, latitude = this.Latitude, longitude = this.Longitude, YearBuilt = this.YearBuilt, LotSize = this.LotSize, FinishedSize = this.FinishedSize, Bedrooms = this.Bedrooms, Bathrooms = this.Bathrooms, UseCode = this.UseCode, HOA = this.HOA, UpdateDate = DateTime.Now }; db.AddToAddresses(address); db.SaveChanges(); In the database i can clearly see that the Trigger ran and updated the neighborhoodID in the address table for the row. I tried to just reload that record to get the assigned id like this: address = (from a in db.Addresses where a.AddressID == address.AddressID select a).First(); In the debugger i can clearly see that the address.AddressID is correct, entity doesn't update in memory. Is there any work around for this?

    Read the article

  • Entity Framework 4 - Delete Object

    - by GibboK
    I have 3 Tables in my DataBase CmsMasterPages CmsMasterPagesAdvSlots (Pure Juction Table) CmsAdvSlots Here a Picture of my EDM: I need find out all objects CmsAdvSlot connected with a CmsMasterPage (it is working in my code posted belove), and DELETE the result (CmsAdvSlot) from the DataBase. My Problem is I am not able to DELETE this Objects when I found theme. Error: The object cannot be deleted because it was not found in the ObjectStateManager. int findMasterPageId = Convert.ToInt32(uxMasterPagesListSelector.SelectedValue); CmsMasterPage myMasterPage = context.CmsMasterPages.FirstOrDefault(x => x.MasterPageId == findMasterPageId); var resultAdvSlots = myMasterPage.CmsAdvSlots; // It is working until here foreach (var toDeleteAdv in resultAdvSlots) { context.DeleteObject(myMasterPage.CmsAdvSlots.Any()); // ERORR HERE!! context.SaveChanges(); } Any idea how to solve it? Thanks for your time! :-)

    Read the article

  • ADO.NET DataService Exception

    - by Ravi
    Hi, I am working on C#.Net with ADO.NET Dataservice. I try to update one record to relational tabel, when I reach context.SetLink() I am getting exception("The context is not currently tracking the entity"). I don't know how to solve this problem. My code is specified below. LogNote dbLogNote =logNote; LogSubSession dbLogSubSession = (from p in context.LogSubSession where p.UID == logNote.SubSessionId select p).First<LogSubSession>() as LogSubSession; context.AddToLogNote(dbLogNote); dbLogNote.LogSubSession = dbLogSubSession; context.SetLink(dbLogNote, "LogSubSession", dbLogSubSession); context.SaveChanges(); Here LogSubSession is a primary table and LogNote is a foreign table. I am updating data into foreign table based on primary key table. Thanks

    Read the article

  • Endless saving of CoreData Context

    - by Robert
    Sometimes I noticed that a 'save:' operation an a ManagedObjectContext never returns and consumes 100% CPU. I'm using an SQL Store in a GarbageCollected environment (Mac OS X 10.6.3). The disk activity shows about 700 KB/s writing. While having a look at the folder that contains the sqlite database file the "-journal" file appears and disappears, appears and disappears, ... This is part of the call graph from the process analysis: 2203 -[NSManagedObjectContext save:] 1899 -[NSPersistentStoreCoordinator(_NSInternalMethods) executeRequest:withContext:] 1836 -[NSSQLCore executeRequest:withContext:] 1836 -[NSSQLCore saveChanges:] 1479 -[NSSQLCore performChanges] ... 335 -[NSSQLCore recordChangesInContext:] ... 20 -[NSSQLCore rollbackChanges] ... 2 -[NSSQLCore prepareForSave:] ... 62 -[NSPersistentStoreCoordinator(_NSInternalMethods) _checkRequestForStore:originalRequest:andOptimisticLocking:] ... 1 -[NSPersistentStore(_NSInternalMethods) _preflightCrossCheck] ... 184 -[NSMergePolicy resolveConflicts:] ... 120 -[NSManagedObjectContext(_NSInternalChangeProcessing) _prepareForPushChanges:] ... Everything a happening in the main GUI thread. Any ideas what I can to do to resolve the problem?

    Read the article

  • Can't update rows in my database using Entity Framework...?

    - by Dissonant
    Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the database I auto-generated an ADO.NET Entity Data Model, and I'm trying to add a new Customer to it like so: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Program { static void Main() { Database1Entities db = new Database1Entities(); Customer c = new Customer(); c.Name = "Harry"; db.AddToCustomer(c); db.SaveChanges(); } } } But it doesn't persist Customer "Harry" to the database! I've been scratching my head for a while now wondering why such a simple operation doesn't work. What on earth could be the problem!?

    Read the article

  • VBA - Prevent Excel 2007 from showing a defined names message box?

    - by John M
    I am working on a Excel 2007 workbook that will contain a macro to save the current sheet (a template) as a PDF file (no problem) a Excel 97-2003 file (problem) When saving the Excel file a messagebox appears asking about "Defined names of formulas in this workbook may display different values when they are recalculated...Do you want Excel to recalculate all formulas when this workbook is opened?". The user can then select Yes/No and then the file will save. How do I disable the messagebox from appearing? The default answer would be 'No'. My code for saving: Sub saveAs_97_2003_Workbook(tempFilePath As String, tempFileName As String) Dim Destwb As Workbook Dim SaveFormat As Long 'Remember the users setting SaveFormat = Application.DefaultSaveFormat 'Set it to the 97-2003 file format Application.DefaultSaveFormat = 56 ActiveSheet.Copy Set Destwb = ActiveWorkbook Destwb.CheckCompatibility = False With Destwb .SaveAs tempFilePath & tempFileName & ".xls", FileFormat:=56 .Close SaveChanges:=False End With 'Set DefaultSaveFormat back to the users setting Application.DefaultSaveFormat = SaveFormat End Sub

    Read the article

  • How do I delete an object from an Entity Framework model without first loading it?

    - by Tomas Lycken
    I am quite sure I've seen the answer to this question somewhere, but as I couldn't find it with a couple of searches on SO or google, I ask it again anyway... In Entity Framework, the only way to delete a data object seems to be MyEntityModel ent = new MyEntityModel(); ent.DeleteObject(theObjectToDelete); ent.SaveChanges(); However, this approach requires the object to be loaded to, in this case, the Controller first, just to delete it. Is there a way to delete a business object referencing only for instance its ID? If there is a smarter way using Linq or Lambda expressions, that is fine too. The main objective, though, is to avoid loading data just to delete it.

    Read the article

  • Which approach to create the data access layer has the highest performance?

    - by pooyakhamooshi
    I have to create a very high performance application. Currently, I am using Entity Framework for my data access layer. My application has to insert some communication data almost every second. I found that Entity Framework is slow; it has about 2 seconds delay to finish the SaveChanges() method. I was thinking I have the following options: 1. Create the data access layer myself using ADO.NET; using stored procedures or ad-hoc queries 2. Use Enterprise Library Data access Layer 3. Use NHibernate 4. Use Repository Factory: http://pooyakhamooshi.blogspot.com/search?q=repository What do you think? which one is quicker for inserting data? Which one is quicker to set up?

    Read the article

  • update database problem with asp.net mvc 2

    - by ognjenb
    [AcceptVerbs(HttpVerbs.Post)] public ActionResult Numbers(int id, int val, int name) { int temp = val % 2; brojevi br = new brojevi(); if (temp == 1 && name == 1) { var nmb = (from n in numbers.brojevi where n.prvi_br == id select n).First(); br.prvi_br = nmb.prvi_br - 1; numbers.SaveChanges(); } var nm = from n in numbers.brojevi select n; return View(nm); } Data table brojevi have 3 fields but I have to change(update) only one of them (prvi_br). Why my solutions doesn't save changes to database

    Read the article

  • Saving a modified object from ASP.NET MVC View Using Entity-Franework 4

    - by Dani
    I retrieve an object graph from DB using EF4. The context is closed as soon as the data retrieve and the data passes to the controller, and then to the view. in the view the data is modified, and then the controller gets it back. From the controller I run Repository.Update(MyEmp); and in my repository the code goes: using (var context = new mydb()) { if (myEmp.ID != 0) // Checking if it's modified or new { context.Emp.Attach(MyEmp); int result = context.SaveChanges(); return myEmp.ID; } } The problem - once attached, the object entityState goes to unchanged, and not modified, and of course - nothing is saved to the database. What am I doing wrong ?

    Read the article

  • mvc3 ActionResult does not reload page if is already on it

    - by senzacionale
    public ActionResult DeleteCategory(int id) { CategoryManager manager = new CategoryManager(); manager.DeleteCategory(id); TempData["IsDeleted"] = true; return RedirectToAction("CategoriesList"); } public ActionResult CategoriesList() { List<CategoryModel> model = new CategoryManager().GetAll(); return View(model); } public void DeleteCategory(int categoryId) { using (AsoEntities context = new AsoEntities()) { var categoryToDelete = (from c in context.Categories where c.Id == categoryId select c).SingleOrDefault(); if (categoryToDelete == null) return; context.Categories.DeleteObject(categoryToDelete); context.SaveChanges(); } } when i delete article i go back to CategoriesList but page is not reloaded if i am already on CategoriesList. What to do that page will be reloaded and data will be changed?

    Read the article

  • How to: Avoid Inserting Related Entities?

    - by niaher
    I have this schema: I want to insert an Order with OrderItems into database, so I wrote this method: public void SaveOrder(Order order) { using (var repository = new StoreEntities()) { // Add order. repository.Orders.AddObject(order); // Add order items. foreach (OrderItem orderItem in order.OrderItems) { repository.OrderItems.AddObject(orderItem); } repository.SaveChanges(); } } Everything is inserted just fine, except that new Product records are inserted too, which is not what I want. What I want is to insert Order and its OrderItems, without going any further down the object graph. How can that be achieved? Any help is really appreciated, thank you.

    Read the article

  • Entity framework Update fails when object is linked to a missing child

    - by McKay
    I’m having trouble updating an objects child when the object has a reference to a nonexising child record. eg. Tables Car and CarColor have a relationship. Car.CarColorId CarColor.CarColorId If I load the car with its color record like so this var result = from x in database.Car.Include("CarColor") where x.CarId = 5 select x; I'll get back the Car object and it’s Color object. Now suppose that some time ago a CarColor had been deleted but the Car record in question still contains the CarColorId value. So when I run the query the Color object is null because the CarColor record didn’t exist. My problem here is that when I attach another Color object that does exist I get a Store update, insert error when saving. Car.Color = newColor Database.SaveChanges(); It’s like the context is trying to delete the nonexisting color. How can I get around this?

    Read the article

  • Delete Entity in Many to Many Relation. Don't get error but entity is not deleted

    - by Shapper
    I have, in EF5, two entities: User and Role. Between User and Role there is a many to many relation. I don't have an entity for the UserRoles database which sets the relation. I have a User and I want to delete a role without loading it from the database. Context context = new Context(); User user = context.Users.First(x => x.Id == 4); user.Roles = new List<Role>(); Role role = new Role { Id = 20 }; context.Roles.Attach(role); user.Roles.Remove(role); context.SaveChanges(); I don't get any error but the role is not removed. Any idea why? Thank you, Miguel

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12  | Next Page >