我使用了 3 個類來構建這個組。
我的資料庫提供程式是 Microsoft SQL Server。
public class GroupType
{
[Key]
public int GroupTypeId { get; set; }
[MaxLength(100)]
public string GroupTypeExpalin { get; set; }
}
public class Groups
{
[Key]
public int GroupId { get; set; }
[MaxLength(200)]
public string GroupName { get; set; }
public GroupType GroupType { get; set; }
}
[Index(nameof(EntityId), nameof(GroupDet), IsUnique = true)] //not allow duplicate Rows
public class GroupDetail
{
[Required]
public string EntityId { get; set; }
[Required]
public Groups GroupDet { get; set; }
}
當我嘗試進行添加遷移時出現此錯誤
屬性“GroupDetail.GroupDet”屬于“Groups”型別,當前資料庫提供程式不支持。更改屬性 CLR 型別,或使用“[NotMapped]”屬性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略該屬性。
uj5u.com熱心網友回復:
這里正確的設計是有一個復合鍵。這樣,您就不需要單獨的唯一索引,并且可以通過將 GroupId 作為前導索引鍵來優化訪問特定組的所有組詳細資訊。
public class Group
{
public int GroupId { get; set; }
public virtual ICollection<GroupDetail> GroupDetails { get; set; } = new HashSet<GroupDetail>();
}
public class GroupDetail
{
[Required]
public int GroupId { get; set; }
[Required]
public string EntityId { get; set; }
public Group Group { get; set; }
}
接著
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Group>();
builder.Entity<GroupDetail>().HasKey(nameof(GroupDetail.GroupId), nameof(GroupDetail.EntityId));
uj5u.com熱心網友回復:
資料庫表不能有 Groups 型別的列。資料庫未知。你必須有這樣的東西:
[Required]
public int GroupId { get; set; }
其中 GroupId 是組的 FK
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517087.html
標籤:C#sql服务器实体框架
