首先是EF6代码 - Identity是表中两列的唯一组合

时间:2015-10-31 01:06:08

标签: sql ef-code-first entity-framework-6

早上好,

我首先使用EF6代码,然后尝试实现以下目标:

我有一个班级/桌子战斗机:

public class Fighter
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int FighterId { get; set; }
    public string Name { get; set; }
}

我想跟踪战士之间不同的胜利数量,所以我创建了另一个类:FightResult

public class FightResult
{
    public virtual Fighter Fighter1 { get; set; }
    public virtual Fighter Fighter2{ get; set; }
    public uint Wins1 { get; set; }
    public uint Wins2 { get; set; }
}

我希望Fighter1和Fighter2的组合是独一无二的。 例如,让我们说这个条目已经存在:

+----------+----------+-------+-------+
| Fighter1 | Fighter2 | Wins1 | Wins2 |
+----------+----------+-------+-------+
| Jon Cena | Yoda     |     0 |     0 |
+----------+----------+-------+-------+

我不希望能够使用相同的战士输入一个条目,例如这两个:

+----------+----------+-------+-------+
| Fighter1 | Fighter2 | Wins1 | Wins2 |
+----------+----------+-------+-------+
| Jon Cena | Yoda     |     0 |     1 |
| Yoda     | Jon Cena |     0 |     0 |
+----------+----------+-------+-------+

使用Entity Framework可能有更好的方法来解决这个问题,如果您有建议我会很乐意阅读它。

由于

1 个答案:

答案 0 :(得分:0)

您可以尝试编写类似这样的东西(它将创建复合主键:Fighter1ID和Fighter2ID,我建议您使用int类型设置键而不是在图片上指定的字符串,尤其是如果Fighter类具有int FighterId,如图所示上文)。

    public class FightResult {

        [Key, Column(Order = 0)]        
        public int Fighter1ID { get; set; }        
        [Key, Column(Order = 1)]        
        public int Fighter2ID { get; set; }        

        public virtual Fighter Fighter1 { get; set; }
        public virtual Fighter Fighter2{ get; set; }
        public uint Wins1 { get; set; }
        public uint Wins2 { get; set; }  
}

然后,在您添加新项目之前,您可以按ID对战士进行排序,例如:

//You have two fighters: fighter1 and fighter2
var firstFighter = fighter1.ID > fighter2.ID ? fighter1 : fighter2;
var secondFighter = fighter1.ID > fighter2.ID ? fighter2 : fighter1;
db.FightResult.Add(new FightResult { Fighter1 = firstFighter, Fighter2 = secondFighter, Wins1 = 1, Wins2 = 0});

另外你可以尝试另一种方法(我建议你先做一个,因为我认为可能是第二个变种的pitfals):

    public class FightResult {    
        [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]       
        public int ID {get; set;}

        public virtual Fighter Fighter1 { get; set; }
        public virtual Fighter Fighter2 { get; set; }
        public uint Wins1 { get; set; }
        public uint Wins2 { get; set; }

        public FightResult(Fighter Fighter1, Fighter Fighter2, uint Wins1, uint Wins2)
        {
            //1. Assign constructor arguments to corresponding instance fields
            //2. Generate uniq ID based on pair of fighters (independently on their order)
            ID = _generateID(Fighter1, Fighter2);
        }
 }