[英]Entity framework. How to right map tables without primary key
我试图解决这个问题,但不能这样,我试图以另一种方式做到这一点。
我有一个由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-barcode表,所以我可能有这样的行:
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 });
}
但是,我看到了这个错误:
严重性代码描述项目文件行抑制状态
错误CS1061'IGrouping'不包含'C_Barcode'的定义,并且没有可以找到接受类型'IGrouping'的第一个参数的扩展方法'C_Barcode'(您是否缺少using指令或程序集引用?)
我怎么解决这个问题?
这只是一个开始; 数据库中有很多其他表没有我希望通过EF使用的键/外键。
没有密钥从表中获取数据的正确方法是什么? 如何映射这些表?
首先,这本身不是主要/外键问题。 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.