如何使EF将数据插入到包含另一个表的键值的表中?
本文关键字:另一个 键值 包含 EF 何使 数据 插入 | 更新日期: 2023-09-27 18:05:58
我有下面的代码,我想用它来添加数据到我的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; }
}
下面是添加方法
的代码 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和testd是身份数据类型。的ApplicationID的正确链接的外键应用程序表到TestAccount表中的ApplicationId。
如何使EF将数据插入到正确的ApplicationID中当它插入到数据库中时,会在TestAccount表中添加什么?
foreach (string applicationName in applicationNames)
{
var app = new Application
{
Name = applicationName,
ModifiedDate = DateTime.Now
});
_uow.Applications.Add(app);
foreach (string testAccountName in testAccountNames)
{
new TestAccount
{
Application = app ,
Name = applicationName,
ModifiedDate = DateTime.Now
});
}
}
不要直接设置ID,设置引用属性,EF会整理剩下的,所以像这样:
....
foreach (string applicationName in applicationNames)
{
_uow.Applications.Add(
new Application
{
Name = applicationName,
ModifiedDate = DateTime.Now,
TestAccounts = (from testAccountName in testAccountNames
select new TestAccount
{
Name = testAccountName ,
ModifiedDate = DateTime.Now
})
}
}