使用实体框架查询数据库不按预期工作

时间:2018-04-24 17:14:26

标签: c# entity-framework

我有当前的表,名为Reviews :(我在sql中直接确认了这个)

Id  Name            Summary         Rating
1   Reviewer one    Review one.     2.5
1   Reviewer two    Review two.     1.5
1   Reviewer three  Review three.   3.9

我试图使用id == 1这是一个外键来获取所有3条评论,但会发生的事情是我第3次获得第一次评论:

Id  Name            Summary         Rating
1   Reviewer one    Review one.     2.5
1   Reviewer one    Review one.     2.5
1   Reviewer one    Review one.     2.5

我的代码有什么问题吗?

public List<Review> GetReviewModels(int restaurantId)  //restaurantId is 1
{
    List<Review> reviews = new List<Review>();
    using (var db = new ReviewEntities())
    {
        reviews = db.Reviews.Where(e => e.id.Equals(restaurantId)).ToList();
    }
    return reviews;
}

以下是审核实体模型:

public partial class Review
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Summary { get; set; }
    public double Rating { get; set; }

    public virtual Restaurant Restaurant { get; set; }
}

3 个答案:

答案 0 :(得分:0)

您的问题出在您的模型应该是您的表/模型中:

public partial class Review
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Summary { get; set; }
    public double Rating { get; set; }
    public int RestaurantId {get;set;}

    public virtual Restaurant Restaurant { get; set; }
}

你需要将它添加到你的Sql:

ALTER TABLE Reviews
DROP CONSTRAINT /*Name of Id fied constraint here*/ 

-- on a side note, you may have to Drop foreign key depending on the way it is in the database

ALTER TABLE Reviews
ALTER COLUMN Id INT NOT NULL PRIMARY KEY IDENTITY(1,1)

ALTER TABLE Reviews
ADD COLUMN RestrauntId INT NOT NULL /*you can make this null if you need*/ FOREIGN KEY FK_Reviews_TO_Restraunt REFERENCES Restraunt(Id)

答案 1 :(得分:0)

更改

reviews = db.Reviews.Where(e => e.id.Equals(restaurantId)).ToList();

reviews = db.Reviews.AsNoTracking().Where(e => e.id.Equals(restaurantId)).ToList();

解决了问题

答案 2 :(得分:0)

您可以通过其他方式尝试此操作。由于评论表引用餐厅表ID,因此餐厅实体模型将具有列表评论,以便获取餐馆ID 1的所有评论,其中: 这是Review Model类。

 public partial class Review
 {
    public int id { get; set; }
    public string Username { get; set; }
    public string Summary { get; set; }
    public double Rating { get; set; }

   public virtual Restaurant Restaurant { get; set; }
 }

这是餐厅模特课

public partial class Restaurant
{
  public int Id{get;set;}
  //Rest all other fields.

  //Foreign key relationship/ Navigation property
  public List<Reviews> Reviews {get;set;}
} 

功能代码如下:

public List<Review> GetReviewModels(int restaurantId)  //restaurantId is 1
{
   List<Review> reviews = new List<Review>();
   using (var db = new RestaurantEntity())
   {
      reviews = db.Restaurant.Where(e => e.id==restaurantId).Select(x=> 
      x.Reviews).FirstOrDefault();
   }
   return reviews;
}