Try this :
Your model
public class FirstClass
{
[Key]
public int Id { get; set; }
public int SecondClassId { get; set; }
[ForeignKey(nameof(SecondClassId))]
[InverseProperty("FirstClasses")]
public virtual SecondClass SecondClass { get; set; }
}
public class SecondClass
{
[Key]
public int Id { get; set; }
[InverseProperty(nameof(FirstClass.SecondClass))]
public virtual ICollection<FirstClass> FirstClasses { get; set; }
}
if you want to have only one first and one second try this code. But I don't recommend it since it will be hard to find the errors.
public class FirstClass
{
[Key]
public int Id { get; set; }
public int SecondClassId { get; set; }
[ForeignKey(nameof(SecondClassId))]
[InverseProperty("FirstClass")]
public virtual SecondClass SecondClass { get; set; }
}
public class SecondClass
{
[Key]
public int Id { get; set; }
[InverseProperty(nameof(FirstClass.SecondClass))]
public virtual FirstClass FirstClass { get; set; }
}
Your db context:
public class FirstClassDbContext : DbContext
{
public FirstClassDbContext()
{
}
public FirstClassDbContext(DbContextOptions<FirstClassDbContext> options)
: base(options)
{
}
public DbSet<FirstClass> FirstClasses { get; set; }
public DbSet<SecondClass> SecondClasses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=localhost;Database=FirstClass;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<FirstClass>(entity =>
{
entity.HasOne(d => d.SecondClass)
.WithMany(p => p.FirstClasses)
.HasForeignKey(d => d.SecondClassId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FirstClass_SecondClass");
});
// or for one to one you can use yours, but I don't recommend it since
//it will be hard to find the errors and it will not do anything for you.
//Only confusing queries.
modelBuilder.Entity<FirstClass>()
.HasOne(f => f.SecondClass)
.WithOne(s => s.FirstClass)
.HasForeignKey(d => d.SecondClassId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_FirstClass_SecondClass");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…