我有以下代码:
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的样品时 ,样品是空的。样品也是ICollection类型。如何将ICollections添加到空的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
AddNew onlu添加了实体,为什么会从Samples中删除样本?
public static TEntity AddNew<TEntity>(this IDbSet<TEntity> self, object fromValues) where TEntity : class
{
return self.Add(Create(self, fromValues));
}
在给予AddNew的object 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中的样本为空。