bunu kullanın:
EF bire bir ilişki kurmak için tek geçerli yol olduğunu
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
[Key, ForeignKey("User")]
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public User User { get; set; }
}
- ayrıca asıl varlığa FK olmalıdır bağımlı varlığın PK. o EF çalışamaz çünkü EF çift yönlü bire-bir ilişki gibi bir şey yoktur.
insanlar bazen bunun üstesinden nasıl yön anapara bağımlı varlıklar + veritabanında elle tanımlanan benzersiz anahtarlar için navigasyon koleksiyonuna sahip değildir iki bire birçok ilişkilerdir.
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
// one side MUST be nullable otherwise you have bidirectional constraint where each
// entity demands other side to be inserted first = not possible
public int? ProfileId { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Ve haritalama size tanımlayacaktır: Yani manuel eşlemesi gerektiren
modelBuilder.Entity<User>
.HasOptional(u => u.Profile)
.WithMany()
.HasForeignKey(u => u.ProfileId);
modelBuilder.Entity<Profile>
.HasRequired(u => u.User)
.WithMany()
.HasForeignKey(u => u.UserId);
Şimdi veritabanında Benzersiz anahtarları tanımlamalısınız - Kodu kullanıyorsanız ilk
custom database initialize r kullanın. Her iki taraf da
Profile
olmadan başka
User
orada olmamalıdır
User
Profile
önce eklemek kez bu kadar BOŞ hala benzersiz değerler dahildir benzersiz FK talep nedeniyle bire-bir hala çift yönlü yanlış bir kavramdır unutmayın. Bu muhtemelen seri hale getirilebilir işleme yol açar.
aldığınız hata nedir? – Eranga