由于EF无法保存基本类型的列表,因此我创建了一个Day对象,该对象仅包含1-7的枚举,并使用迁移种子方法来填充数据库。所以在数据库表中我的值为1到7。
public class Day
{
[Key]
public Days DayOfWeek { get; set; }
public virtual ICollection<SalaryAddition> SalaryAdditions { get; set; }
}
我在OnModelCreating中设置了SalaryAddition和Day之间的连接。
modelBuilder.Entity<SalaryAddition>()
.HasMany(s => s.Days)
.WithMany(s => s.SalaryAdditions)
.Map(ss =>
{
ss.MapLeftKey("SalaryAdditionId");
ss.MapRightKey("SalaryAdditionDay");
ss.ToTable("SalaryAdditionDays");
});
我的问题是,为了向我的SalaryAddition对象添加Day,我需要从数据库加载它。但我想做的就是这样:
salaryAddition.Days.Add(new Day{DayOfWeek = Days.Monday});
所以我不需要用数据库中的数字加载一个数字。
但是当我这样做时,我得到:
Violation of PRIMARY KEY constraint 'PK_dbo.Days'. Cannot insert duplicate key in object 'dbo.Days'.
答案 0 :(得分:3)
最好使用我认为的标志枚举
[Flags]
public enum DaysOfWeek
{
None = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64,
All = 127
}
然后在你的SalaryAddition
课程中,你只有
public DaysOfWeek Days { get; set; }
然后你可以做像
这样的事情if(salaryAddition.Days.HasFlag(DaysOfWeek.Monday))
{
Console.WriteLine("This salary addition is linked to Monday");
}
并设置一天的旗帜
salaryAddition.Days |= DaysOfWeek.Monday;
或取消设置标志
salaryAddition.Days &= ~DaysOfWeek.Monday;