[英]Entity Framework + Composite Keys with Duplicates
I am trying to store a matrix in a database using a code-first model with Entity Framework. 我正在尝试使用带有实体框架的代码优先模型在数据库中存储矩阵。 I have created an object for each element in the matrix.
我为矩阵中的每个元素创建了一个对象。 I want to be able to search both rows and columns so I was hoping to have both my
RowID
and ColID
as Key
. 我希望能够同时搜索行和列,因此希望将
RowID
和ColID
作为Key
。 Using composite keys I am still getting the error: 使用组合键,我仍然收到错误:
"Trojan.Models.Matrix_Element: : EntityType 'Matrix_Element' has no key defined. Define the key for this EntityType.
“ Trojan.Models.Matrix_Element::EntityType'Matrix_Element'没有定义关键字。为此实体类型定义关键字。
default_Matrix: EntityType: EntitySet 'default_Matrix' is based on type 'Matrix_Element' that has no keys defined."
“ default_Matrix:EntityType:EntitySet'default_Matrix'基于未定义键的类型'Matrix_Element'。”
I am guessing that this is because there are duplicate values for RowID
and ColID
. 我猜这是因为
RowID
和ColID
有重复的值。 It is a matrix so every pair (RowID, ColID)
is unique but I am guessing that because there are multiple entries per row and multiple entries per column it considers there being elements with the same PK. 它是一个矩阵,因此每一对
(RowID, ColID)
都是唯一的,但我猜是因为每行有多个条目,每列有多个条目,因此它认为存在具有相同PK的元素。
Is there a way to identify an element ONLY by the pair of keys? 有没有一种方法只能通过键对来识别元素? Or am I forced to create an
ElementID
attribute and use that as a PK? 还是我被迫创建
ElementID
属性并将其用作PK?
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Trojan.Models
{
public class Matrix_Element
{
[Key, Column(Order = 0)]
public int RowID;
[Key, Column(Order = 1)]
public int ColID;
public int? cellValue;
public string R;
}
}
You need to use properties rather than fields. 您需要使用属性而不是字段。 Change your class to this....
将您的班级更改为此。
public class Matrix_Element
{
[Key, Column(Order = 0)]
public int RowID { get; set; }
[Key, Column(Order = 1)]
public int ColID { get; set; }
public int? cellValue { get; set; }
public string R { get; set; }
}
....and you will get a migration like this: ....您将获得如下迁移:
public override void Up()
{
CreateTable(
"dbo.Matrix_Element",
c => new
{
RowID = c.Int(nullable: false),
ColID = c.Int(nullable: false),
cellValue = c.Int(),
R = c.String(),
})
.PrimaryKey(t => new { t.RowID, t.ColID });//Success!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.