我有以下两个课程:
conn
我想用作EF6上下文的。
我通过以下方式定义了上下文:
public class Record
{
public int RecordId { get; set; }
public DateTime? InsertDate { get; set; } = DateTime.Now;
public DateTime BookingDate { get; set; }
public string AmountTypeName { get; set; }
public double? Amount { get; set; }
public string BookingAccountID { get; set; }
public string AccountCurrency { get; set; }
public string ClientCurrency { get; set; }
public string AffectsBalance { get; set; }
public double? AmountAccountCurrency { get; set; }
public string AmountClientCurrency { get; set; }
public int UnifiedInstrumentCode { get; set; }
public InstrumentInfo InstrumentInfo { get; set; }
}
public class InstrumentInfo
{
[Key]
public int UnifiedInstrumentCode { get; set; }
public ICollection<Record> Record { get; set; }
public string AssetType { get; set; }
public int UnderlyingInstrumentUic { get; set; }
public string UnderlyingInstrumentSubType { get; set; }
public string InstrumentSymbol { get; set; }
public string InstrumentDescription { get; set; }
public string InstrumentSubType { get; set; }
public string UnderlyingInstrumentAssetType { get; set; }
public string UnderlyingInstrumentDescription { get; set; }
public string UnderlyingInstrumentSymbol { get; set; }
}
如果我对它进行测试,该测试将向数据库添加InstrumentInfo对象
public class TransactionsContext: DbContext
{
public DbSet<Record> Records { get; set; }
public DbSet<InstrumentInfo> InstrumentInfos { get; set; }
public TransactionsContext()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<TransactionsContext>(null);
base.OnModelCreating(modelBuilder);
}
}
我收到以下异常:
SqlException:无法将值NULL插入列 “ UnifiedInstrumentCode”,表 'TransactionsContext.dbo.InstrumentInfoes';列不允许 空值。 INSERT失败。该声明已终止。
我尝试了发现here的所有不同情况,但是我不知道自己在做什么错。
最终目标是我以一种方式定义我的两个类,以便通过“ UnifiedInstrumentCode”属性将“ Record”链接到“ InstrumentInfo”表。 我的猜测是我对这两个表的约束仍然不正确,但是我无法弄清楚如何在EF6中定义它(代码优先)才能使它正常工作。
答案 0 :(得分:0)
在我的InstrumentInfo的主键中添加注释[DatabaseGenerated(DatabaseGeneratedOption.None)] 解决了该问题:
reviews_list
我没有进一步调查,但我的猜测是,如果添加了新的Record,EF会首先创建一个InstrumentInfo对象,该对象的主键具有Null值,从而导致异常。
希望以后有人遇到同样的问题会有所帮助。