如何在没有导航的情况下定义外键 属性
How to define Foreign Key without having navigation property
我关注类:
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; }
}
我不需要从 CompanyDetail 导航到 Company,所以我没有导航 属性。
公司可能有 CompanyDetail,但这不是必需的。
预期的设计有一个名为 CompanyDetail 的 table,Company_Id 是 PK 和 FK(对公司 table)
创建模型时,收到以下错误:
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.
我需要了解如何使用 Fluent API 或数据注释解决问题。
您需要为 CompanyDetail 定义 [Key]
尝试
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)
我关注类:
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; }
}
我不需要从 CompanyDetail 导航到 Company,所以我没有导航 属性。
公司可能有 CompanyDetail,但这不是必需的。
预期的设计有一个名为 CompanyDetail 的 table,Company_Id 是 PK 和 FK(对公司 table)
创建模型时,收到以下错误:
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.
我需要了解如何使用 Fluent API 或数据注释解决问题。
您需要为 CompanyDetail 定义 [Key]
尝试
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)