Entity framework Context.SaveChanges not working at all - c#

I'm having problems with this code. I´m able to connect to an mdf example database archive and generate the entity model. Althought I´m able to query the context model and retrieve information from the DB, when I try to update, delete or insert anything in the context and translate the changes to the DB Context.SaveChanges is not working. There is no Exception, the Entity model is updated properly, but the DB does not have the change.
Thanks in regard
public void addCourse(int courseId, int deptId, string courseTitle)
{
SchoolContexto = new SchoolEntities();
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
SchoolContexto.Courses.Add(mycourse);
SchoolContexto.SaveChanges();
SchoolContexto.Dispose();
}

Make property of .mdf file in your solution as
Copy to output Directory: "Copy only if newer"
Otherwise your db file will overwrite every time it runs

i suggest you to use this code :
public void addCourse(int courseId, int deptId, string courseTitle)
{
SchoolEntities entities = new SchoolEntities();
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
entities.Courses.Add(mycourse);
entities.SaveChanges();
}
if this is not working i suggest you to check your app.config file :)

Another way to add a new entity to the context is to change its state to Added. Have you tried this
using (var entities = new SchoolEntities())
{
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
context.Entry(mycourse).State = EntityState.Added;
entities.SaveChanges();
}

I think the Problem is that you working on localdb (.mdf) file .
I had the same problem but when i created new (sql server database connection)
Server name : (localdb)\MSSqlLocaldb .... it worked

A little off the subject but just in case you're here because you're performing an update and not an add, Check if you need a key on the table. I had a similar issue with EF Core. During an update on a table no error was generated but the SaveChanges returned 0. It wasn't until I tested adding a record, that it generated the key error. I resolved the key issue and the update went fine.

It happens because probably you don't have primary key in your Course entity.

I solved the problem by including the following namespace
using System.Data.SqlClient;

Related

I can query mysql DB but not save changes to it

I had created a system using Visual Studio 2015 with a SQLServer database, i could query the DB but not save changes to it. So i created the database inside Visual Studio. I now tried to create the database in MySQL workbench and have the same issue. I switched to mysql as i was unsure if i had correctly installed My SQL Server, i have definately installed mysql properly as i have used it for projects in Java.
I created the database using a code first technique and this worked fine. Any ideas?
Connection String from appsettings
"DataAccessMySqlProvider": "server=localhost;port=3306;database=rentalsdb;userid=root;password=******"
In Startup.cs
var sqlConnectionString = Configuration.GetConnectionString("DataAccessMySqlProvider");
services.AddMvc();
services.AddDbContext<RentalsDbContext>(options =>
options.UseMySQL(
sqlConnectionString,
b => b.MigrationsAssembly("RentalsRated.Web")));
services.AddDbServiceDependencies(sqlConnectionString);
In my repo then
public bool CreateUser(UserAccount user)
{
if (user != null)
{
try
{
_Context.UserAccounts.Add(user);
_Context.Entry(user).State = EntityState.Modified;
_Context.SaveChanges();
return true;
}
catch ....
I can see the right variables come to here. It all worked fine with the database in visual studios server explorer.
Thanks!
IndexOutOfRangeException: Index was outside the bounds of the array.
The Stack trace: at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)...
UPDATE: Works when i comment out my data that is being passed as Byte[].
Root cause:
Password and salt fields are defined as blobs. Change the type of the password and salt fields to one of the string types instead.
Masking issue:
You were changing the state of the entity to Modifed right after adding it to the table which might corrupt the internal state of the context.
MSDN is recommending two different ways of adding new entity to the context
https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113).aspx
1) By adding the entity directly to the table.
using (var context = new BloggingContext())
{
var blog = new Blog { Name = "ADO.NET Blog" };
context.Blogs.Add(blog);
context.SaveChanges();
}
2) By changing the state of the entity to Added
using (var context = new BloggingContext())
{
var blog = new Blog { Name = "ADO.NET Blog" };
context.Entry(blog).State = EntityState.Added;
context.SaveChanges();
}

Why Entity Framework still has wrong count and wrong "vision of data"

I am using EF with Oracle..
I have a test that will run this bit of code
using (var ctx = new Entities())
{
ctx.SOMEOBJECTSESSIONs.Add(
new SOMEOBJECTSESSION()
{
SOMEOBJECTSESSIONID = 0,
SOMEOBJECTSESSIONIDHASH = hash,
DEVICEDESC = "some device",
OPERATINGSYSTEMDESC = "Microsoft Windows NT 6.1.7601 Service Pack 1",
BROWSERDESC = "Chrome27",
IPADDRESS = "123.132.123.132",
SOMEOBJECTSESSIONSTATUSID = 9999999999,
CREATEDBYSOMEOBJECTID = 9999999999,
CREATEDDATE = DateTime.Now,
UPDATEDBYSOMEOBJECTID = 9999999999,
UPDATEDDATE = DateTime.Now
}
);
ctx.SaveChanges()
}
Using this I add a record to the database.. I then went into the database and manually deleted that record..
When I try and run this test again, the call to SaveChanges dies, just sits there.. Now If I do a
var tmp = ctx.SOMEOBJECTSESSIONs.Count();
I get back a count that is one more than what is in the database.. Which to me suggests EF still has a hook locally to the record I deleted..
I have read numerous articles about refreshing context(didn't work). I have cleared the "Local"
ctx.SOMEOBJECTSESSIONs.Local.Clear()
which also did not work..
I would have thought that the fact I am spawning up a new Entities connection it should be getting the data from the database..
How do I fix this? What am I doing wrong?
Cheers,
J
Create your context as late as possible and dispose it as soon as you are ready.
So preferably dispose it and create a new one; or use Reload, as described in Entity Framework Refresh context?.

Add an entity as LOG during property changing events of another entity

I am using linq to sql in a windows form application. there is a bug that I couldn't find the solution until now!
partial void OnAmountChanging(int? value)
{
OrderLog lg = new OrderLog()
{
Date = DateTime.Now,
IPAddress = System.Net.Dns.GetHostAddresses(Environment.MachineName)[0].ToString(),
NewData = value,
OldData = this.Amount,
Status = "Changed",
User = User.CurUser,
Order = this // each Order has one-to-many relation to OrderLog entity.
};
}
this is run as soon as the value of AMOUNT changes in datagridview.
after closing the form I try to save the created log to Database:
db.SubmitChanges();
then I face this error :
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported
is there any solution?

Saving an entity to the DB in WinForms

I've looked at so many posts about this, but still haven't found the solution:
I'm using a winforms app that uses EntityFramework (6?). When I load the form I can read from the DB using the context (Entities). However, when I savechanges after adding a new entity, it doesn't persist to the db.
var c = new Card { Name = tbName.Text, Quantity = int.Parse(tbQuantity.Text) };
dbContext.Cards.Add(c);
dbContext.SaveChanges();
The dbContext is setup in the form constructor and is an instance of "LiquorTrackEntities".
LiquorTrackEntities dbContext;
public Form1()
{
InitializeComponent();
dbContext = new LiquorTrackEntities()
Reading from the db works:
var cards = dbContext.Cards.ToList();
I do this stuff all the time in asp.net MVC, but it isn't working in WinForms.. is there something special I have to do in winforms? I also know about the normal "using (var db = new LiquorEntitiesEntities())" convention, but I just want to get this functioning before I worry about convention.
Any ideas?
Just tried this to no avail:
var c = new Card { Name = tbName.Text, Quantity = int.Parse(tbQuantity.Text) };
dbContext.Cards.Attach(c);
dbContext.Entry(c).State = EntityState.Added;
dbContext.SaveChanges();
Just tried creating a new EDMX using EF5 instead.. same problem.
UPDATE:
SaveChanges does return a 1 when after adding a card. It stays in the context (if I reload my cards from the context, the new one is there..) but never makes it to the database.

Problem adding objects in Entity Framework, I'm guessing it's a problem with my database model

My problem is that I'm trying to add a child entity, but keep running into problems.
Here's my situation:
I have a bunch of Profiles.
Each Profile has a bunch of CategoryPriorities attached to it.
Each CategoryPriorities has one AttributePriority attached to it.
When I update my model in Visual Studio I get the following:
I can without any trouble get the following to work:
CategoryPriority _categoryPriority = new CategoryPriority();
Profile _profile = DB.GetProfile(ProfileID);
_profile.CategoryPriorities.Add(_categoryPriority);
DB.savechanges()
But somehow the following will not work:
AttributePriority _attributePriority = new AttributePriority();
CategoryPriority _categoryPriority = new CategoryPriority();
_categoryPriority.AttributePriorities.Add(_attributePriority);
// Error! There is no option of "Add" or any other operation for the matter.
Profile _profile = DB.GetProfile(ProfileID);
_profile.CategoryPriorities.Add(_categoryPriority);
DB.savechanges()
I'm guessing this is due to how the EF model is set up.
Ideally I would like to have an one-to-one between CategoryPriority and AttributePriority tables.
I'll add an image of my model.
Any ideas?
Any help much appreciated!
Edit:
I've added images to my post.
Funny thing is that if I write:
Profile _p = new Profile();
There is no option of _p.Add there either.. obviously I'm missing something..
Edit 2:
Ok, so I got it to work, almost...
I know, not the most aesthetically pleasing code, I'm working on that..
Profile _profile = this.GetProfile(this.GetUserID(arrangeattributesviewmodel.ProfileID));
int iter = 0;
foreach (AttributeListForCategory _category in arrangeattributesviewmodel.AllAttributesForCheckBoxList.CategoryAttributeList)
{
iter++;
CategoryPriority _categoryPriority = new CategoryPriority();
_categoryPriority.ProfileID = arrangeattributesviewmodel.ProfileID;
_categoryPriority.CategoryID = _category.CategoryID;
_categoryPriority.CategoryName = _category.CategoryName;
_categoryPriority.CategoryID = _category.CategoryID;
_categoryPriority.CategoryPriorityNR = iter;
AttributePriority _attributePriority = new AttributePriority();
_attributePriority.AttributePriorityString = _category.CompilePriorityString();
_categoryPriority.AttributePriority = _attributePriority;
_profile.CategoryPriorities.Add(_categoryPriority);
db.SaveChanges(); // It fails here with the message below..
}
{"A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'CategoryPriorityID'."}
Any ideas?
Edit 3:
Solved it!
I had to instanciate an AttributePriority in my CategoryPriority...
Your relation between CategoryPriority and AttributePriority is 1:0..1 so there is not Add method. You simply call:
_categoryPriority.AttributePriority = attributePriority;
Btw. how is it possible that your entity define AttributePriority but your code uses AttributePriorities? It should not compile.
Make sure you have foreign keys set up correctly and then regenerate your model.

Categories