1

I have this piece of code:

var data = context.Accounts.Where(a => a.UserName == User.Identity.Name).Select(a => a.UserAddons).SingleOrDefault();
if (data == null)
   data = new UserAddons();
{setting up properties of data}
context.SaveChanges();

I want it to create a new row of UserAddons. But it doesn't want to. Do i need to select whole Account entity to do that?

1
  • 2
    You need to add the new entity to the context Commented Jan 2, 2013 at 13:59

2 Answers 2

1

You're probably forgetting to add the new entity to the context. Try this (not tested):

bool isNew = false;
var data = context.Accounts.Where(a => a.UserName == User.Identity.Name).Select(a => a.UserAddons).SingleOrDefault();

if (data == null)
{
   data = new UserAddons();
   isNew = true;
}  

// setting up properties of data

if(isNew)
    context.Add(data);

context.SaveChanges();
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah. But then i will need to look for the Account entity for the second time, to properly associate entities. :-/
Then you need to load the Account entity first with the associated UserAddons. If there aren't any, create the new entity. PS: Are you using a DbContext or ObjectContext?
I'm using DbContext. Why does that matter?
1

If I understand your model correctly, you should add the new UserAddons to the Account

var account = context.Accounts.Where(a => a.UserName == User.Identity.Name).Single();

if (account.Addons == null)
   account.UserAddons = new UserAddons();

{setting up properties of account.Addons}

context.SaveChanges();

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.