2016-10-25 74 views
1

I tried to solve this problem, but couldn't所以我试图做另一种方式。实体框架。如何正确映射表没有主键

我有一个视图,包含3个没有任何主键/外键的表。

VS2015生成的这个类:

[Table("SkuBarcodesView")] 
public partial class SkuBarcodesView 
{ 
    [Key] 
    [Column("_Code", Order = 0)] 
    [StringLength(11)] 
    public string C_Code { get; set; } 

    [Key] 
    [Column("_Description", Order = 1)] 
    [StringLength(150)] 
    public string C_Description { get; set; } 

    [Key] 
    [Column("_ProductCode", Order = 2)] 
    [StringLength(50)] 
    public string C_ProductCode { get; set; } 

    [Key] 
    [Column("_Ref", Order = 4)] 
    [StringLength(36)] 
    public string C_Ref { get; set; } 

    [Key] 
    [Column("_Barcode", Order = 5)] 
    public string C_Barcode { get; set; } 
} 

这个实体代表SKU条码表,所以我可以有行的像这样的:

Product | Barcode 
-------- | -------- 
product0 | barcode0 
product1 | barcode1 
product2 | barcode2 
product2 | barcode2 

现在,我需要以某种方式组吧。我想:

using (skumodel db = new skumodel()) 
{ 
    var query = db.SkuBarcodesViews.GroupBy(e => e.C_Ref) 
     .Select(g => new { Barcode = g.C_Barcode }); 
} 

但是,后来我看到这个错误:

Severity Code Description Project File Line Suppression State

Error CS1061 'IGrouping' does not contain a definition for 'C_Barcode' and no extension method 'C_Barcode' accepting a first argument of type 'IGrouping' could be found (are you missing a using directive or an assembly reference?)

我该如何解决这个问题?

这只是一个开始;数据库中还有很多其他表没有我想通过EF使用的键/外键。

从没有密钥的表中获取数据的正确方法是什么?如何映射这些表?

+0

如果你的观点不具有主键,你为什么用'[关键]'属性? –

+0

该类是ado.net模型自动生成的。顺便说一句,我可以使用字段_ref像一个键,因为没有任何键属性我得到EntityType'SkuBarcodesView'没有定义键。定义此EntityType的关键字。 – zxyzxy

+0

如果您使用现有数据库,则不是Code First。 – Gasper

回答

0

首先,这本身并不是主键/外键问题。 LINQ分组不像通常的SQL分组,但更像是一个Dictionary。对于您的示例,对于表中的每个事件,具有密钥product2的组将具有两个值barcode2。正如我们在C#中的对象进行操作,每排由SkuBarcodesView实例来表示,所以你需要这样的事情,如果你想获得该产品的所有条形码:

using (skumodel db = new skumodel()) 
{ 
    var query = db.SkuBarcodesViews.GroupBy(e => e.C_Ref) 
     .Select(g => new { 
          Product = g.Key, 
          Barcodes = g.Select(x => x.C_Barcode) 
       }); 
} 

注意,对于现在有没有限制在你的表格中的价值,所以一个产品可能有很多不同的条形码或许多相同的条形码等。你怎么知道哪一个是正确的?当然,如果您确定只有类似的条形码,您可以在上面的代码中执行g.First().C_Barcode而不是内部的g.Select()以获得单个条形码。

其次,使用GroupBy()这里是一个矫枉过正,你可以使用类似:

using (skumodel db = new skumodel()) 
{ 
    var query = db.SkuBarcodesViews 
     .Select(x => new { Ref = x.C_Ref, Barcode = x.C_Barcode }) 
     .Distinct(); 
}