Data annotation - Entity framework - Foreign key

entity-framework

Question

I have the following classes and utilize data annotation with EF:

[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 should I beautify get; set; public virtual DbLicense License's property?

toss EF

'DbLicense' and 'DbAccount' type associations cannot be resolved at the primary end. The relationship fluent API or data annotations must be used to explicitly specify the primary end of this association.

This is effective:

modelBuilder.Entity<DbAccount>()
            .HasRequired(x => x.License)
            .WithRequiredPrincipal();

However, how could I express this using annotations?

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

Popular Answer

Entity Framework demands that the dependent's main key also serve as the foreign key when setting up one-to-one connections.

Instead, try this:

[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