我收到此错误
System.ArgumentNullException:'值不能为null。参数名称:实体'
这是我的代码:
namespace CodeFirstFinal
{
class Program
{
public static Category category { get; private set; }
static void Main(string[] args)
{
using (var db = new CategoryContext())
{
Console.Write("Enter a name for a new Error category:");
var name = Console.ReadLine();
var blog = new Category { Name = name };
db.Categories.Add(category);
db.SaveChanges();
var query = from c in db.Categories
orderby c.Name
select c;
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
}
}
}
public class Category
{
public int? CategoryId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual List<Error> Errors { get; set; }
}
public class Error
{
public int? ErrorId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int? CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class User
{
[Key]
public string Username { get; set; }
public string DisplayName { get; set; }
}
public class CategoryContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Error> Errors { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Property(u => u.DisplayName)
.HasColumnName("display_area");
}
}
}
此代码行上发生错误:
db.Categories.Add(category);
我是编程新手,不胜感激。
谢谢!
答案 0 :(得分:1)
var name = Console.ReadLine();
var category = new Category { Name = name };
db.Categories.Add(category);
您需要编写上述代码,希望能解决您的问题。
答案 1 :(得分:0)
您没有初始化Category属性,因此将其作为空值传递给Add方法,这是一个错误。您可以初始化Category属性或传递Blog变量。