问题
How do I get the following relationship to only generate the FK in Entity2?
public class Entity1
{
public int Id { get; set; }
public virtual Entity2 Entity2 { get; set; }
}
public class Entity2
{
public int Id { get; set; }
public int? Entity1Id { get; set; }
public virtual Entity1 Entity1 { get; set; }
}
I want Entity1 be able to get a reference to an Entity2 (have EF lazy load it), but I don't want Entity1 to have an FK to Entity2 in the db, I just want Entity2 to have an FK to Entity1. Is this possible? Everything I have been trying in OnModelCreating in my db context isn't getting me what I really want.
The closest I can get is this:
modelBuilder.Entity<Entity2>().HasOptional(e => e.Entity1).WithOptionalDependent(e => e.Entity2);
However, this will create the Entity2 table with an Entity1Id column AND an Entity1_Id FK column to Entity1, instead of just creating the single Entity1Id column that should be an FK to Entity1.
Also, in case anyone asks, the Entity1Id property is intentionally a nullable int because a Entity2 instance/table record needs to exist independently without a link to Entity1.
回答1:
Remove the code in OnModelCreating, and add this annotation to your Entity2
public class Entity2
{
public int Id { get; set; }
[ForeignKey("Entity1")]
public int? Entity1Id { get; set; }
public virtual Entity1 Entity1 { get; set; }
}
Or you can try this (I don't know if it work or not)
modelBuilder.Entity<Entity2>()
.HasOptional(e => e.Entity1)
.WithOptionalDependent(e => e.Entity2)
.Map(m => { m.MapKey("Entity1Id"); });
来源:https://stackoverflow.com/questions/27027895/one-to-one-relationship-with-fk-in-one-direction