I have an Entity Framework application using ASP.NET Identity 2.2 (i.e., my context inherits from IdentityDbContext<T> and I have a User class that inherits from IdentityUser). I am successfully seeding the AspNetUsers table using the following calls in my seed method:

var testUser = new User() {
  UserName = "TestUser",
  Email = "TestUser@Domain.tld"

manager.Create(testUser, "TestPassword");

I have extended the model to include a Post class which includes a reference to my User class:

public class Post {

  public Post() {}

  public int Id { get; set; }

  public User User { get; set; }


And, of course, this corresponds to the following in my User class:

public class User : IdentityUser {

  public User() : base() {
    this.Posts = new HashSet<Post>();

  public ICollection<Post> Posts { get; set; }

  //Additional members...

I am then seeding the Posts collection with the following:

 var testPost = new Post() { Id = 1, User = testUser };

   post => post.Id,

Technically, this works fine; the Post instance is created, and the automatically generated User_Id field is correctly populated with the Id of the newly created User instance.

So what's the problem? Every time it runs, I get the following in my EntityValidationErrors: "The User field is required". It doesn't prevent my application from working, but it makes it difficult to detect legitimate errors.

Obviously, I could add custom code to my DbContext.SaveChanges() method in order to ignore this error, but I'd rather understand why it's happening in the first place, particularly if there's a problem with how I'm seeding my data.

Related posts

Recent Viewed