我正在制作一个在.net核心6中使用剃须刀页面的实习生网站。数据库已经存在,并用于另一个.net应用程序。这个数据库没有外键,主键只是技术密钥。这些主键不是我在SQL中可以用来链接表的字段。我遵循教程,我成功地从我的数据库中搭建了我的模型(所以说是白口外键引用),我成功地为我的数据库的表创建了简单的CRUD页面。但是现在我必须创建使用许多按字段链接的表的页面,我尝试了在模型或模型构建器中手动配置,但是失败了。
下面可以看到示例中的代码:在“类别”表中,指向"Document“的字段链接是Category.Code
namespace MyWebApp.Models
{
public partial class Category
{
public int Id { get; set; }
public string Code { get; set; } = null!;
public string label{ get; set; } = null!;
public bool Enable { get; set; }
}
}
在“文档”表中,指向“类别”的字段链接是Document.CodeCat。文件只涉及一个类别。类别可以引用一个或多个文档。
namespace MyWebApp.Models
{
public partial class Document
{
public int Num { get; set; }
public string? Id { get; set; }
public string? Codecat { get; set; }
public DateTime? Datedoc { get; set; }
public DateTime? Modified { get; set; }
public DateTime? Datedel { get; set; }
}
}
谢谢你的帮助。
发布于 2022-08-24 11:45:55
我不得不做两件事:
首先,在这两个模型中指定链接,如下所示:
public partial class Category
{
public int Id { get; set; }
public string Code { get; set; } = null!;
public string label{ get; set; } = null!;
public bool Enable { get; set; }
public ICollection<Document> Documents { get; set; }
}
public partial class Document
{
public int Num { get; set; }
public string? Id { get; set; }
public string? Codecat { get; set; }
public Category Category { get; set;}
public DateTime? Datedoc { get; set; }
public DateTime? Modified { get; set; }
public DateTime? Datedel { get; set; }
}
然后,指定哪些字段用于链接上下文中的表:
modelBuilder.Entity<Document>()
.HasOne(d => d.Category)
.WithMany(c => c.Documents)
.HasForeignKey(d => d.Codecat)
.HasPrincipalKey(c => c.Code);
发布于 2022-08-18 08:46:36
您需要按以下方式更改模型,然后运行Add-Migration
然后运行Update-database
:
public partial class Category
{
public int Id { get; set; }
public string Code { get; set; } = null!;
public string label { get; set; } = null!;
public bool Enable { get; set; }
public ICollection<Document> Documents { get; set; }
}
public partial class Document
{
public int Num { get; set; }
public string? Id { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
public DateTime? Datedoc { get; set; }
public DateTime? Modified { get; set; }
public DateTime? Datedel { get; set; }
}
EF
可以自动检测foreign key
,不需要编写任何代码,但是如果您想手动处理并控制它,可以如下所示:
builder.Entity<Docuemnt>(e =>
{
e.HasOne(x => x.Category).WithMany(x => x.Documents).HasForeignKey(x => x.CategoryId).IsRequired(false);
});
https://stackoverflow.com/questions/73399409
复制相似问题