ASP.NET MVC - EF Code First不希望在我的数据库中创建行

时间:2013-01-02 13:57:29

标签: c# .net asp.net-mvc entity-framework

我有这段代码:

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行。但它不想。我是否需要选择整个帐户实体来执行此操作?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

如果我正确理解您的模型,您应该将新的UserAddons添加到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();