我正在使用带有WAF框架的MVVM。 WAF Framework包含一个名为EntityCollection的类:
public sealed class EntityCollection<TEntity> : RelatedEnd, ICollection<TEntity>, IEnumerable<TEntity>, IEnumerable, IListSource where TEntity : class
{
public EntityCollection();
public int Count { get; }
public bool IsReadOnly { get; }
public void Add(TEntity entity);
public void Attach(IEnumerable<TEntity> entities);
public void Clear();
public bool Contains(TEntity entity);
public void CopyTo(TEntity[] array, int arrayIndex);
public ObjectQuery<TEntity> CreateSourceQuery();
public IEnumerator<TEntity> GetEnumerator();
public override void Load(MergeOption mergeOption);
public void OnCollectionDeserialized(StreamingContext context);
public void OnSerializing(StreamingContext context);
public bool Remove(TEntity entity);
}
但是,我需要使用LINQ TO XML。检查函数GetExamProduced,我有一个属性Exercises,其中是一个EntityCollection,我需要从GetExercises(xml)添加所有,但我遇到问题,因为数据类型。提前谢谢。
编辑: 情况是,我想插入或添加从ExamProduced返回函数GetExercises到Execises属性的练习。
我的问题是演员。 Exercises属性是EntityCollection数据类型,另一个是IEnumerable。如何将IEnumerable中的所有项插入到EntityCollection中。
public ExamProduced GetExamProduced(XElement xml)
{
var examProduced = new ExamProduced
{
ExamProducedID = (int)xml.Attribute("ExamID"),
Date = (DateTime)xml.Attribute("Date"),
Seed = (int)xml.Attribute("Seed"),
Exercises = GetExercises(xml)
};
return examProduced;
}
public EntityCollection<Exercise> GetExercises(XElement xml)
{
var objs =
from objective in xml.Descendants("Objective")
where (bool)objective.Attribute("Produced")
let id = (int)objective.Attribute("ID")
select new Exercise
{
ExerciseID = id,
MakeUp = (bool)objective.Attribute("MakeUp"),
Quantify = (byte)(int)objective.Attribute("Quantify"),
Score = (float)objective.Elements().Last().Attribute("Result")
};
return (EntityCollection<Exercise>)objs;
}
答案 0 :(得分:1)
首先,EntityCollection
是Entity Framework的一部分而不是WAF。其次,假设您的类Exercise
是实体数据模型的一部分,那么您只需将Excercise
实例添加到新的EntityCollection实例并返回它:
public EntityCollection<Exercise> GetExercises(XElement xml)
{
var objs =
from objective in xml.Descendants("Objective")
where (bool)objective.Attribute("Produced")
let id = (int)objective.Attribute("ID")
select new Exercise
{
ExerciseID = id,
MakeUp = (bool)objective.Attribute("MakeUp"),
Quantify = (byte)(int)objective.Attribute("Quantify"),
Score = (float)objective.Elements().Last().Attribute("Result")
};
var entityCollection = new EntityCollection<Exercise>();
foreach(var exercise in objs) {
entityCollection.Add(exercise);
}
return entityCollection;
}
答案 1 :(得分:0)
我觉得你需要在TEntity和XELement之间进行映射。您可以使用 AutoMapper框架就是这样做的。
http://automapper.codeplex.com/
我知道这与问题无关,但是如果你想要转换为int
不要使用(int)objective.Attribute("ID")
,请使用TryParse,同样适用
对于所有转换,如果值为null,您将获得Exception。