在我的数据库中,我有一个表类别,列ID,CategoryName,ParentCategoryId,其中ParentCategoryId对Category.Id有约束.
我首先使用实体框架代码,实体看起来像:
public class Category
{
public long Id { get; private set; }
public string CategoryName { get; private set; }
public long? ParentCategoryId { get; private set; }
public Category ParentCategory { get; private set; }
public virtual ICollection<Category> SubCategories { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试对此运行查询,我会得到异常:
The relationship 'ComplaintModel.FK_Complaint_Category' was not loaded because the type 'ComplaintModel.Category' is not available.\r\nThe following information may be useful in resolving the previous error:\r\nThe required property 'Category1' does not exist on the …Run Code Online (Sandbox Code Playgroud) c# mapping entity-framework relational-database ef-code-first
我在这里发现了很多类似的问题,但似乎没有一个问题可以解决我的问题.流畅的api和属性没有帮助.数据库已创建,但在向其添加对象时,它已崩溃.我想要一个拥有自己的集合的类.这是我的代码:
[Table("UObjects")]
public class UObject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Browsable(false)]
public long ID { get; set; }
public string Name { get; set; }
[Browsable(false)]
public long? ParentID { get; set; }
public virtual UObject UParent { get; set; }
[Browsable(false)]
public virtual ICollection<UObject> UObjects { get; set; }
}
public class MyContext : DbContext
{
public DbSet<UObject> UObjects { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// This fluent API didn't help
//modelBuilder.Entity<UObject>()
// .HasOptional(u => u.UParent)
// …Run Code Online (Sandbox Code Playgroud)