c# - 一个表属性与两个表属性 .NET MVC 有关系
问题描述
我有一个名为News的表,我想存储高质量和低质量的图像以及每个新的信息,所以我创建了另一个名为NewsAttachment的表,该表应该与News有关系,但我已经有另一个名为NewsComment的表也与News有关系,当我想将两者都定义为外键时,SQL Server 在News和NewsAttachment中添加另一列。
这是新闻类:
public class News
{
[Key]
public int NewsId { get; set; } //primary key
.
.
.
//navigation property
public virtual List<Comments> Comments { get; set; }
public virtual List<NewsAttachments> Comments { get; set; }
public News()
{
}
}
这是评论类:
public class Comments
{
[Key]
public int CommentId { get; set; }
[Required]
public int NewsId { get; set; } //Foreign key of News
.
.
.
//navigation property
public virtual News News { get; set; }
public Comments()
{
}
}
这是NewsAttachment类:
public class NewsAttachment
{
[Key]
public int NewsAttachmentId { get; set; }
[Required]
public int NewsId { get; set; } //Foreign key of News
//Image information property
public string FileName { get; set; }
public string RealFileName { get; set; }
public string FilePath { get; set; }
public string FilePageType { get; set; }
//navigation property
public News News { get; set; }
public NewsAttachment()
{
}
}
我的问题总结: 我希望News中的 NewsId与表中的其他两个属性有关系,但它遇到了麻烦。
如果无法解决这个问题,请给我另一种方法来将我的两张照片及其信息保存在我的数据库中。
解决方案
您必须专门向 EF 声明它,以便它知道哪个是外键:
public class NewsAttachment
{
[Key]
public int NewsAttachmentId { get; set; }
public int NewsId { get; set; } //Foreign key of News
//Image information property
public string FileName { get; set; }
public string RealFileName { get; set; }
public string FilePath { get; set; }
public string FilePageType { get; set; }
[ForeignKey("NewsId")]
public News News { get; set; }
public NewsAttachment()
{
}
}
推荐阅读
- html - 如何让这个 div 高于另一个 div?
- html - 发送到另一个容器时删除属性元素
- c# - c#如何获取具有多个相同字符的子字符串
- reactjs - 运行测试时出错 - jest.mock 不是函数
- javascript - NestJS + TypeORM - 连接到 mysql 和 mongodb 时出错
- python - Increment the counter column when encountered a specific value in another column
- amazon-web-services - CloudFormation 无法创建 AlexaSkill - 找不到资源
- rpm - 使用 venv 和 rpm 在内部部署 python 应用程序
- c# - 基于具有逗号分隔值的列创建多个 DataTable 行
- excel - 如何使用宏将“缩进级别”转换为 SUBTOTAL 公式?