LINQ select on a SQL View gets wrong answer

后端 未结 7 1376
猫巷女王i
猫巷女王i 2021-01-05 02:07

I have a SQL View that produces a response with 8 columns. Its a rather complicated so I won\'t list it here and it won\'t add much to the issue I\'m trying to understand.

7条回答
  •  爱一瞬间的悲伤
    2021-01-05 02:58

    Your problem is similar to this: Using a view with no primary key with Entity

    Specify keys that makes your row unique. You can specify those keys on your entity mapping via attributes:

    public class YearlySalesOnEachCountry
    {        
        [Key, Column(Order=0)] public int CountryId { get; set; }
        public string CountryName { get; set; }
        [Key, Column(Order=1)] public int OrYear { get; set; }
    
        public long SalesCount { get; set; }      
        public decimal TotalSales { get; set; }
    }
    

    Or you can do it via code approach:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);    
        modelBuilder.Entity()
               .HasKey(x => new { x.CountryId, x.OrYear });     
    }
    

提交回复
热议问题