Reputation: 113
I have an existing entity, called Person. The Person entity has an ID. A Person can exsist on it's own.
In a new application, I am creating an entity called Dog. The database model for this new entity is created using EF code first. I now want to add the rule that a Dog Must have an owner, Person. A Person can have many Dogs.
I have generated the edmx to have a PersonContext available in my application.
I now want to make the correct reference between the 2 entities.
public class DogContext : DbContext
{
public DogContext()
: base("DefaultConnection")
{
}
public DbSet<Dog> Dogs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Person>().HasMany<Dog>(p => p.Dogs).WithRequired(d => d.Person).HasForeignKey(u => u.DogId);
base.OnModelCreating(modelBuilder);
}
}
[Table("Dog")]
public class Dog
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DogId{ get; set; }
public string Name{ get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
The Person class is generated in the .edmx file and has no knownledge of which dogs he owns at the moment. The important thing right now is the Dog having an owner, being a Person.
With this setup I get the error:
EntityType 'Person' has no key defined. Define the key for this EntityType. Person: EntityType: EntitySet 'Person' is based on type 'Person' that has no keys defined.
I guess this is EF code first throwing an error.
Question: How can I specify the Key on Person while keeping code first from also creating this in the db model?
thanks
Upvotes: 0
Views: 111
Reputation: 2497
What does your Person
class look like. Person
needs either an property named Id or PersonId
or a property which is marked as an ID.
Also you need to mark your foreign key:
public int PersonId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
Otherwise Entity Framework tends not to recognize that PersonId
is related to your Person
property.
Upvotes: 1