4

I'm trying to use the code below to add an entry in the 'UserAlertSubscriptions' table in my db which just links users to alertconfigurations.

The problem is that although i get no errors the entry does not get added to the database.

Any idea what i'm doing wrong. As you can see, I tried ApplyAllChanges, but this made no difference.

AlerterDataEntities alerterDataEntities = new AlerterDataEntities()

// get current user
User user = alerterDataEntities.Users.Where(u => u.UserID == 1).ToList<User>()[0];

// get selected alert configuration
AlertConfiguration alertConfiguration =
    alerterDataEntities.AlertConfigurations.Where(a => a.AlertConfigurationID == 3).ToList
        <AlertConfiguration>()[0];

UserAlertSubscription userAlertSubscription = new UserAlertSubscription
{
    User = user,
    AlertConfiguration = alertConfiguration
};

user.UserAlertSubscriptions.Add(userAlertSubscription);
//alerterDataEntities.AcceptAllChanges();
alerterDataEntities.SaveChanges();
4
  • 1
    var user = alerterDataEntities.Users.First(u => u.UserID == 1) Commented May 12, 2011 at 13:53
  • thanks SLaks, that does make it much neater code and i've used 'First' as suggested for user ans alertconfiguration...but alas it still does not savethe relationship to the database. Commented May 12, 2011 at 14:03
  • That's why it's a comment rather than an answer. I have no idea what the problem is. Commented May 12, 2011 at 14:04
  • The weird thing is I can see in the debugger after the '.SaveChanges' that there is an extra item in there (in alerterDataEntities.UserAlertSubscriptions). Weirder still i have a textblock in my view bound to the count of the items in that table and when i run it straight after according to the count its there...but in the database it's not. I assume this is some sort of caching...when i look again later, the count of the table is back to what it actually is Commented May 12, 2011 at 15:14

1 Answer 1

3

All fixed - I found the problem was that the database was being copied to the output directory each time I ran it. So the table I was looking at (the one in the root of my application) was not the one it had added to.

This post solved by @Jean-Lois was where I found the solution: C# Entitity framework SaveChanges() not working

To solve it I set the database 'Copy to output directory' to 'Do not copy' and put the full file path in the database connection string in the app.config

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.