Приведение IEnumerable к EntityCollection? - PullRequest
0 голосов
/ 16 декабря 2011

Я использую MVVM с WAF-фреймворком. WAF Framework содержит класс с именем EntityCollection<T>:

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<Exercise>, и мне нужно добавить все из GetExercises (xml), но у меня возникают проблемы, потому что типы данных.

EDIT: Ситуация такова, что я хотел бы вставить или добавить упражнения, которые возвращают функцию GetExercises, в свойство Exercises из ExamProduced.

Моя проблема - актерский состав. Свойство Exercises имеет тип данных EntityCollection<Exercise>, а другое - 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;
    }

Ответы [ 2 ]

1 голос
/ 16 декабря 2011

Прежде всего, EntityCollection является частью Entity Framework , а не WAF.Во-вторых, предполагая, что ваш класс Exercise является частью модели данных Entity, вы можете просто добавить экземпляры 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;
}
0 голосов
/ 16 декабря 2011

Я думаю, что вам нужно отобразить между TEntity и XELement.Для этого можно использовать платформу AutoMapper.

http://automapper.codeplex.com/

Я знаю, что это не связано с вопросом, но если вы хотите привести к int, не используйте (int)objective.Attribute("ID"), используйте TryParse , то же самое относится ко всем кастам, если значение будет нулевым, вы получите исключение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...