Reputation: 3610
I have a base class that looks like this:
public abstract class BaseEntity
{
[Required]
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
[Required]
public int CreatedByUserId { get; set; }
public int ModifiedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
[ForeignKey("ModifiedByUserId")]
public virtual User ModifiedBy { get; set; }
}
And I want to use this class as the base for every other class. Also for the User class, because users are created and modified by other users.
public class User : BaseEntity
{
[Key]
public int UserId { get; set; }
....
}
But I get this error:
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I researched the error, and it all became quite clear. EF has to be told how these entities relate to eachother, and which entity to save first, and which comes second. But among all the examples/solutions, I did not find any similar case. Can anyone help me out with this? I'd prefer to have this fixed by using data annotations.
Upvotes: 1
Views: 505
Reputation: 426
Well, I don't know any good solution for this with data annotation but using Fluent API can help you in a very clear way. You should override OnModelCreating method in your DbContext class
public class MyDbContext : DbContext
{
DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasRequired<User>(x => x.CreatedBy)
.WithMany();
modelBuilder.Entity<User>()
.HasRequired<User>(x => x.ModifiedBy)
.WithMany();
}
}
That's how you could describe two self-referencing one-to-many relationship.
Upvotes: 2