Reputation: 12646
Entity Framework isn't reacting to my data annotation changes in this particular scenario, so I want to try through Fluent API, which I never use.
I have a model "Transfer" which has three properties - its Id and "TransferredFromId" and "TransferredToId" properties, which represent Users (another EF model) involved in the transfer. Like so:
public class Transfer
{
public long Id { get; set; }
public long TransferredFromId { get; set; }
[ForeignKey("TransferredFromId")]
public User TransferredFrom { get; set; }
public long TransferredToId { get; set; }
[ForeignKey("TransferredToId")]
public User TransferredTo { get; set; }
}
The user model currently looks like this:
public class User
{
public long Id { get; set; }
[InverseProperty("TransferredFrom")]
public ICollection<Transfer> TransferredFroms { get; set; }
[InverseProperty("TransferredTo")]
public ICollection<Transfer> TransferredTos { get; set; }
}
Note - I think user can look like this and it would still work:
public class User
{
public long Id { get; set; }
}
How do I achieve the exact same thing through Fluent API?
To clarify, I want to have a transfer table which has two properties, which both represent the Id from the Users table.
Temporary edit: Should my models look like this when I switch to Fluent API?
public class Transfer
{
public long Id { get; set; }
public long TransferredFromId { get; set; }
public long TransferredToId { get; set; }
}
and
public class User
{
public long Id { get; set; }
}
and then add this in context?
modelBuilder.Entity<Transfer>().HasRequired(x => x.TransferredFrom).WithMany(x => x.TransferredFroms).HasForeignKey(x => x.TransferredFromId);
modelBuilder.Entity<Transfer>().HasRequired(x => x.TransferredTo).WithMany(x => x.TransferredTos).HasForeignKey(x => x.TransferredToId);
Upvotes: 0
Views: 91
Reputation: 1059
two possibilities, depending on which side you want to start on.
first, you have to override the OnModelCreating() method in your context.
your two options should look like:
modelBuilder.Entity<Transfer>().HasRequired(x=>x.TransferredFrom).WithMany(x=>x.TransferredFroms).HasForeignKey(x=>x.TransferredFromId);
modelBuilder.Entity<Transfer>().HasRequired(x=>x.TransferredTo).WithMany(x=>x.TransferredTos).HasForeignKey(x=>x.TransferredToId);
and
modelBuilder.Entity<User>().HasMany(x=>x.TransferredFroms).WithRequired(x=>x.TransferredFrom).HasForeignKey(x=>x.TransferredFromId);
modelBuilder.Entity<User>().HasMany(x=>x.TransferredTos).WithRequired(x=>x.TransferredTo).HasForeignKey(x=>x.TransferredToId);
each Set of these 2 lines should have the same semantics as your data annotation mapping.
Upvotes: 3