Elisabeth
Elisabeth

Reputation: 21226

Assign UserId to my child entity results in a 2n UserId1 column in the sql table

I am using

asp.net core 
asp.net core identity 
entity framework core

My User entity has a child navigation property 'Projects' because a User can have many Projects and a Project entity has one User navigation property:

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }

    public User User { get; set; }
}

When I update my database with the migrations then in the Project sql table a column UserId is created which is also the foreign key to User.Id.

That happend all automatically by convention.

But when I want to save a new project with the related userId

context.Projects.Add(project);
project.User.Id = userId; // User is null here
await context.SaveChangesAsync();

I just get an exception. I can also write:

project.User = new User{ Id = userId };
await context.SaveChangesAsync();

How can store that project entity with just that userId without retrieving the whole user again?

P.S. When I create an additional UserId property in the project entity then another UserId column is created in the sql table with the name 'UserId1'.

UPDATE

public class Project
{ 

    public int Id { get; set; }
    public string Name { get; set; }

    public User User { get; set; }
}

 modelBuilder.Entity<Project>().HasOne(x => x.User).WithMany(p => p.Projects).IsRequired();

Upvotes: 1

Views: 462

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109255

You're almost there. If you use your code in this order:

context.Projects.Add(project);
project.User = new User{ Id = userId };
await context.SaveChangesAsync();

... you only have to add one more line:

context.Projects.Add(project);
project.User = new User{ Id = userId };

context.Attach(project.User);

await context.SaveChangesAsync();

Now Entity Framework knows that the user is an existing user and it will use its ID as foreign key for project. In this case, project.User is a so-called stub entitiy: an incomplete entity object that's used to avoid a roundtrip to the database.

As an alternative, you can add a property UserId to Project, which will be picked up by EF as foreign key belonging to Project.User.

Upvotes: 1

Related Questions