【发布时间】:2020-03-24 06:58:31
【问题描述】:
我有以下两个类:
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; }
}
我想用作 EF6 的上下文。
我通过以下方式定义了上下文:
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);
}
}
如果我对其进行测试,将向数据库添加 InstrumentInfo 对象
[TestMethod]
public void AddInstrumentInfo_Added_IsTrue()
{
InstrumentInfo info = FakeFactory.GetInstrumentInfo();
using (var ctx = new TransactionsContext())
{
ctx.InstrumentInfos.Add(info);
ctx.SaveChanges();
}
}
我得到以下异常:
SqlException:无法将值 NULL 插入列 'UnifiedInstrumentCode',表 'TransactionsContext.dbo.InstrumentInfoes';列不允许 空值。插入失败。声明已终止。
我尝试了所有我发现 here 的不同场景,但我不知道我做错了什么。
最终目标是我以某种方式定义我的两个类,以便通过“UnifiedInstrumentCode”属性将“Record”链接到“InstrumentInfo”表。 我的猜测是我对这两个表的约束仍然不正确,但我不知道如何在 EF6(代码优先)中定义它以使其正常工作。
【问题讨论】:
-
您的测试方法是否将数据添加到数据库?!
-
你需要在
UnifiedInstrumentCode之上的属性[ForeignKey("InstrumentInfo")]或流利的代码来定义关系。
标签: c# entity-framework entity-framework-6 constraints