1

我有这段代码:

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();

我希望它创建一个新的 UserAddons 行。但它不想。我是否需要选择整个帐户实体才能做到这一点?

4

2 回答 2

1

您可能忘记将新实体添加到上下文中。试试这个(未测试):

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();
于 2013-01-02T14:04:41.657 回答
1

如果我正确理解您的模型,您应该将新的添加UserAddonsAccount

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();
于 2013-01-02T14:20:46.940 回答