我有以下代码:
ICollection<Sample> samples = new Collection<Sample>();
samples.Add(sample1);
samples.Add(sample2);
Order record = scope.DbContext.Orders.AddNew(new Order
{
Name = GenerateName("Order"),
Samples = samples
});
当我查看样本时,它包含 sample1 和 sample2。但是,当我将它添加到 Order 的 Samples 时,Samples 是空的。Samples 也是 ICollection 类型。如何将 ICollection 添加到空的 ICollection?
更新:
我打印样本并记录时的结果。中间样本:
samples
Count = 2
[0]: {iVention.Lifescience.Test.ElectronicSignatureRepositoryTest.SignHierarchyTest.Sample one.2012-04-21 11:07:24}
[1]: {iVention.Lifescience.Test.ElectronicSignatureRepositoryTest.SignHierarchyTest.Sample two.2012-04-21 11:07:24}
record.Samples
{System.Data.Objects.DataClasses.EntityCollection<iVention.Database.Sample>}
[System.Data.Objects.DataClasses.EntityCollection<iVention.Database.Sample>]: {System.Data.Objects.DataClasses.EntityCollection<iVention.Database.Sample>}
Count: 0
IsReadOnly: false
更新 2:
AddNew onlu 添加实体,为什么这会从 Samples 中删除样本?
public static TEntity AddNew<TEntity>(this IDbSet<TEntity> self, object fromValues) where TEntity : class
{
return self.Add(Create(self, fromValues));
}
在赋予 AddNew 的对象 formValues 中,Samples 仍然包含 2 个样本。
添加看起来像这样:
public static TEntity Create<TEntity>(this IDbSet<TEntity> self, object fromValues) where TEntity : class
{
TEntity returnValue = self.Create();
var targetProperties = typeof(TEntity).GetProperties();
{
var targetProperty = targetProperties.Single(c => c.Name == property.Name);
if (targetProperty.CanWrite && property.GetIndexParameters().Length == 0)
{
if (targetProperty.PropertyType.IsGenericType && targetProperty.PropertyType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>))
{
}
else
{
targetProperty.SetValue(returnValue, property.GetValue(fromValues, null), null);
}
}
return returnValue;
}
因此,当它是 ICollection 时,不会向 returnValue 添加任何内容。returnValue 中的样本为空。