首页 > 解决方案 > 一个表属性与两个表属性 .NET MVC 有关系

问题描述

我有一个名为News的表,我想存储高质量和低质量的图像以及每个新的信息,所以我创建了另一个名为NewsAttachment的表,该表应该与News有关系,但我已经有另一个名为NewsComment的表也与News有关系,当我想将两者都定义为外键时,SQL Server 在NewsNewsAttachment中添加另一列。


这是新闻类:

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与表中的其他两个属性有关系,但它遇到了麻烦。

如果无法解决这个问题,请给我另一种方法来将我的两张照片及其信息保存在我的数据库中。

标签: c#asp.netsql-serverasp.net-mvcentity-framework

解决方案


您必须专门向 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()
    {

    }
}

推荐阅读