Reputation: 322
public class Message
{
[Key]
public int MeesageId { get; set; }
public int SenderId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Sender { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Receiver { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public bool Seen { get; set; }
}
public class Person
{
public string Username { get; set; }
[Key]
public int PersonId { get; set; }
}
I'm getting this error:
The ForeignKeyAttribute on property 'Receiver' on type 'Finder.Models.Message' is not valid. The foreign key name 'PersonId' was not found on the dependent type 'Finder.Models.Message'. The Name value should be a comma-separated list of foreign key property names.
What I think I should do is rename ReceiverId
to PersonId
, so it matches the foreign key, but then the property names would be too messy. Any help would be appreciated
Upvotes: 1
Views: 117
Reputation: 121
It is better to use fluent api.
for example :
public class Message
{
public int MeesageId { get; set; }
public int SenderId { get; set; }
public virtual Person Sender { get; set; }
public int ReceiverId { get; set; }
public virtual Person Receiver { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public bool Seen { get; set; }
}
public class Person
{
public string Username { get; set; }
public int PersonId { get; set; }
public List<Message> SenderMessages { get; set; }
public List<Message> RecieverMessages { get; set; }
}
public class MessageConfigurations : IEntityTypeConfiguration<Message>
{
public void Configure(EntityTypeBuilder<Message> builder)
{
builder.HasKey(x => x.MeesageId);
builder.HasOne(x => x.Sender)
.WithMany(x => x.SenderMessages)
.HasForeignKey(x => x.SenderId)
.OnDelete(DeleteBehavior.NoAction);
builder.HasOne(x => x.Receiver)
.WithMany(x => x.RecieverMessages)
.HasForeignKey(x => x.ReceiverId)
.OnDelete(DeleteBehavior.NoAction);
}
}
public class PersonConfigurations : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.HasKey(x => x.PersonId);
}
}
Upvotes: 0
Reputation: 88852
The ForeignKey attribute specifies which int
property is the foreign key for the specified navigation property. So
public class Message
{
[Key]
public int MeesageId { get; set; }
public int SenderId { get; set; }
[ForeignKey("SenderId")]
public virtual Person Sender { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("ReceiverId")]
public virtual Person Receiver { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public bool Seen { get; set; }
}
Upvotes: 2