【问题标题】:one table property have relation with two table properties .NET MVC一个表属性与两个表属性 .NET MVC 有关系
【发布时间】:2021-04-09 04:08:47
【问题描述】:

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

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

【问题讨论】:

  • 如果任何新闻有多个 unicue 附件,我认为没有任何问题。如果相同的附件可以用于不同的新闻?

标签: c# asp.net sql-server asp.net-mvc entity-framework


【解决方案1】:

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

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多