我想使用以下代码将数据添加到我的 EF 数据库:
var applicationNames = new[] {
"C",
"E",
"S" };
var testAccountNames = new[] {
"Production",
"Ready",
"Beta",
"Alpha" };
foreach (string applicationName in applicationNames)
{
_uow.Applications.Add(
new Application
{
Name = applicationName,
ModifiedDate = DateTime.Now
});
foreach (string testAccountName in testAccountNames)
{
new TestAccount
{
ApplicationID = ??
Name = applicationName,
ModifiedDate = DateTime.Now
});
}
}
_uow.Commit();
这是我的课程:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
public partial class TestAccount
{
public TestAccount()
{
this.Subjects = new List<Subject>();
}
public int TestAccountId { get; set; }
public string Name { get; set; }
public int ApplicationId { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Application Application { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
}
这是我用于 add 方法的代码
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
这是映射:
public TestAccountMap()
{
// Primary Key
this.HasKey(t => t.TestAccountId);
// Relationships
this.HasRequired(t => t.Application)
.WithMany(t => t.TestAccounts)
.HasForeignKey(d => d.ApplicationId);
}
请注意,在数据库中 ApplicationId 和 TestId 是身份数据类型。我还有一个外键,可以将 Application 表的 ApplicationID 正确链接到 TestAccount 表中的 ApplicationId。
如何使 EF 在插入数据库时将数据插入到 TestAccount 表中的正确 ApplicationID 中?