Data annotation - Entity framework - Foreign key

entity-framework

Question

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?

1
2
1/11/2012 5:54:27 PM

Popular Answer

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; }
}
7
2/20/2013 11:07:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow