Home > OS >  Entity structure misinterpreting a class as a context entity
Entity structure misinterpreting a class as a context entity

Time:12-31

In my project I have a Client entity. This entity makes use of an Address class which in turn is not an entity.

public class Client{
  public int Id { get; set;}
  public string Name { get; set;}
  public Address Address { get; set;}
}

public class Address {
  public string City { get; set;}
  public string Country { get; set;}
}

The data entered in the Address class will be persisted in the Client entity. The address class is only used for code organization and reuse.

When uploading the entity framework core context I get the following error:

The entity type 'Address' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

Address is not mapped in context as a DbSet and yet the entity tries to map it. Why? Has anyone ever experienced this?

How do I make the entity understand that class Address is just a complement of class Customer and not an entity itself.

CodePudding user response:

Address is not mapped in context as a DbSet and yet the entity tries to map it. Why?

Because it's a property of an Entity, so will be mapped by default.

By convention, types that are exposed in DbSet properties on your context are included in the model as entities. Entity types that are specified in the OnModelCreating method are also included, as are any types that are found by recursively exploring the navigation properties of other discovered entity types.

Entity Types

Mark it as an Owned Type and it will be mapped to columns on the owning entity's table.

  • Related