【问题标题】:Entity Framework Navigation Property One-to-Many becomes One-to-One实体框架导航属性一对多变成一对一
【发布时间】:2012-07-05 17:16:28
【问题描述】:

在我的数据库中,我有一个一对多的关系(乐队有很多专辑)。但是,当 Album 中的外键受到限制时,这种关系就变成了一对一的关系。

public class Band
{
    [Key]
    public int BandID { get; set; }

    //Other fun attributes

    public virtual ICollection<Album> Albums { get; set; }
}

public class Album
{
    [Key]
    public int AlbumID { get; set; }

    public int BandID { get; set; }

    //Other fun attributes

    //Some other foreign key
    public int SomeOtherKey { get; set; }
}

应该生成的SQL

SELECT * FROM Band
LEFT JOIN Album ON (Band.BandID = Album.AlbumID AND Album.SomeOtherKey = 12)

我的问题是我是否应该在 Band 中拥有另一个导航属性 public virtual Album Album,或者因为这并不总是正确的那将是一个坏主意?我应该使用 LINQ 吗?使用实体框架和模型完成此任务的最简单方法是什么?

【问题讨论】:

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


    【解决方案1】:

    答案不是使用导航属性,而是使用带有新模型的 Linq 查询来保存结果......

    var query =
        from band in Context.Band
        join album in Context.Albums on album.BandID equals band.BandID into j1
        from j2 in j1.Where(x => x.SomeOtherKey == value).DefaultIfEmpty()
        select new BandWithAlbumModel
        {
            Band = band,
            Album = j2
        };
    
    
    public class BandWithAlbumModel
    {
         public Band Band { get; set; }
    
         public Album Album { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      如果你添加

      public virtual Album Album;
      

      这会与

      冲突
      public virtual ICollection<Album> Albums { get; set; }
      

      第一个意味着1:1的关系,而后者意味着1:N的关系。

      由于一个乐队可能有多个(或没有)专辑(此处为领域知识 :-),因此 ICollection 可能是您最想要的。

      根据您的需要,您可能需要添加

      public virtual Band Band { get; set;}
      

      Album

      我不明白你的意思

      但是,当 Album 中的外键受到限制时,这种关系就变成了一对一。

      你能澄清一下这句话吗?

      【讨论】:

      • 是的。基本上,一旦 Album 表中的 SomeOtherKey 字段受到限制(通过 WHERE Album.SomeOtherKey = ?),Album 和 Band 之间的关系就会变成一对一的关系。我确实在专辑中有乐队导航属性,但我希望我的查询生成一个列表,它需要先检查专辑表。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      相关资源
      最近更新 更多