Reputation: 6693
I have following classes:
public class Company
{
public Guid Id { get; set; }
public string Name { get; set; }
public CompanyDetail CompanyDetail { get; set; } // This is optional
}
public class CompanyDetail
{
public Guid Company_Id { get; set; } // This supposed to be PK and the FK to Company
public string ContactName { get; set; }
public string WebSite { get; set; }
public string Phone { get; set; }
}
I don't need to navigate from CompanyDetail to Company so I don't have navigation property.
A Company may have CompanyDetail but it is not required.
The expected design is having a table named CompanyDetail and the Company_Id is the PK as well as FK (to Company table)
When I create the model, I receive following error:
EntityType 'CompanyDetail' has no key defined. Define the key for this EntityType. CompanyDetails: EntityType: EntitySet 'CompanyDetails' is based on type 'CompanyDetail' that has no keys defined.
I need to how I can resolve the issue using Fluent API or Data Annotation.
Upvotes: 1
Views: 124
Reputation: 5284
You need to define [Key] for CompanyDetail
try
public class Company
{
[Key]
public Guid Id { get; set; }
public virtual CompanyDetail CompanyDetail { get; set; } // This is optional
}
public class CompanyDetail
{
[Key]
public Guid Company_Id { get; set; }
}
...
modelBuilder.Entity<Company>()
.HasOptional<CompanyDetail>(u => u.CompanyDetail)
Upvotes: 1