I use Data annotation with EF and I have the classes:
[Table("Accounts")]
public class DbAccount
{
public int Id { get; set; }
public string Username { get; set; }
public virtual DbLicense License { get; set; }
}
[Table("Licenses")]
public class DbLicense
{
public int Id { get; set; }
public int AccountId { get; set; }
[ForeignKey("AccountId")]
public virtual DbAccount Account { get; set; }
}
How I must decorate the property public virtual DbLicense License { get; set; } ?
EF throw
Unable to determine the principal end of an association between the types 'DbLicense' and 'DbAccount'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
This work well:
modelBuilder.Entity<DbAccount>()
.HasRequired(x => x.License)
.WithRequiredPrincipal();
But how i can write this with annotation using?
When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key.
Try this instead:
[Table("Accounts")]
public class DbAccount
{
[Key]
public int Id { get; set; }
public string Username { get; set; }
[InverseProperty("Account")]
public virtual DbLicense License { get; set; }
}
[Table("Licenses")]
public class DbLicense
{
[Key, ForeignKey("Account")]
public int Id { get; set; }
public int AccountId { get; set; }
[InverseProperty("License")]
public virtual DbAccount Account { get; set; }
}