代码之家  ›  专栏  ›  技术社区  ›  Cédric Boivin

更新实体框架中的现有实体集合

  •  1
  • Cédric Boivin  · 技术社区  · 14 年前

    我尝试使用到实体的链接,并且我希望在应用程序中直接使用我的实体。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Calandar.Business.Manager.Data;
    
    namespace Calandar.Business.Models.Args
    {
        public class SaveExpertArgs
        {
            public ExpertEntity Expert { get; set; }
            public SaveExpertArgs(ExpertEntity expert)
            {
                Expert = expert;
            }
        }
    }
    
    public ExpertEntity SaveExpert(SaveExpertArgs args)
    {            
        string connString = ConfigurationManager.ConnectionStrings["CalendarContainer"].ConnectionString;
    
        using (CalendarContainer dbContext = new CalendarContainer(connString))
        {             
            ExpertEntity expert = (from e in dbContext.ExpertEntities
                                   where e.ExpertIdentifier == args.Expert.ExpertIdentifier
                                   select e).FirstOrDefault();
            if (expert == null)
            {
                args.Expert.ExpertIdentifier = Guid.NewGuid();
                dbContext.AddToExpertEntities(args.Expert);
            }
            else
            {
                dbContext.ExpertEntities.ApplyCurrentValues(args.Expert);               
    
                foreach (TimeSlotEntity t in args.Expert.TimeSlotEntities)
                {
                    dbContext.TimeSlotEntities.ApplyCurrentValues(t);
                }
            }              
    
            dbContext.SaveChanges();
            return args.Expert;
        }
    }
    

    我试图保存我的专家实体,它正在工作,但我不知道如何保存我的专家实体的实体集合。有人能帮我吗?

    2 回复  |  直到 14 年前
        1
  •  0
  •   Slappy    14 年前

    试着去掉其他的:

    public ExpertEntity SaveExpert(SaveExpertArgs args)
    {            
        string connString = ConfigurationManager.ConnectionStrings["CalendarContainer"].ConnectionString;
    
        using (CalendarContainer dbContext = new CalendarContainer(connString))
        {             
            ExpertEntity expert = (from e in dbContext.ExpertEntities
                                   where e.ExpertIdentifier == args.Expert.ExpertIdentifier
                                   select e).FirstOrDefault();
            if (expert == null)
            {
                args.Expert.ExpertIdentifier = Guid.NewGuid();
                dbContext.AddToExpertEntities(args.Expert);
            }
            //else
            //{
                dbContext.ExpertEntities.ApplyCurrentValues(args.Expert);               
    
                foreach (TimeSlotEntity t in args.Expert.TimeSlotEntities)
                {
                    dbContext.TimeSlotEntities.ApplyCurrentValues(t);
                }
            //}              
    
            dbContext.SaveChanges();
            return args.Expert;
        }
    }
    
        2
  •  0
  •   Cédric Boivin    14 年前

    好的,我找到了更新实体集合的方法。

    public ExpertEntity SaveExpert(SaveExpertArgs args)
            {
    
                string connString = ConfigurationManager.ConnectionStrings["CalendarContainer"].ConnectionString;
                using (CalendarContainer dbContext = new CalendarContainer(connString))
                {
                    ExpertEntity expert = (from e in dbContext.ExpertEntities
                                           where e.ExpertIdentifier == args.Expert.ExpertIdentifier
                                           select e).FirstOrDefault();
                    if (expert == null)
                    {
                        args.Expert.ExpertIdentifier = Guid.NewGuid();
                        dbContext.AddToExpertEntities(args.Expert);
                    }
                    else
                    {
                        dbContext.ExpertEntities.ApplyCurrentValues(args.Expert);
                        GenericUpdateEntityCollection(args.Expert.TimeSlotEntities, dbContext);
                    }
                    dbContext.SaveChanges();
                    return args.Expert;
                }
            } 
    
    
    private void GenericUpdateEntityCollection<T>(EntityCollection<T> collection, ObjectContext dbContext)
                where T : EntityObject, new()
            {
                int count = collection.Count();
                int current = 0;
                List<T> collectionItemList = collection.ToList();
                bool isAdded = false;
                while (current < count)
                {
                    Object obj = null;
                    // Essai de récupéré l'objet dans le context pour le mettre à jour
                    dbContext.TryGetObjectByKey(collectionItemList[current].EntityKey, out obj);
                    if (obj == null)
                    {
                        // Si l'objet n'existe pas, on en créer un nouveau
                        obj = new TimeSlotEntity();
                        // On lui donne l'entity Key du nouvelle objet
                        ((T)obj).EntityKey = collectionItemList[current].EntityKey;
                        // On l'ajoute au context, dans le timeslot
                        dbContext.AddObject(((T)obj).EntityKey.EntitySetName, obj);
                        // On récupère l'objet du context qui à le même entity key que le nouveau recu en pramètre, le but est d'avoir un context d'attacher
                        dbContext.TryGetObjectByKey(collectionItemList[current].EntityKey, out obj);
                        // On change l'état de l'objet dans le context pour modifier, car 
                        dbContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified);
                        // On change l'état de l'objet passé en paramètre pour qu'il soit au même state que celui dans le context
                        collection.CreateSourceQuery().Context.ObjectStateManager.ChangeObjectState(collectionItemList[current], System.Data.EntityState.Modified);
                        // On place notre flag pour dire que nous avons ajouter dans le context les donnée
                        isAdded = true;
                    }
    
                    if (obj != null)
                    {
                        // On applique les changements de l'objet passé en parametre à celui dans le context
                        dbContext.ApplyCurrentValues<T>(((T)obj).EntityKey.EntitySetName,collectionItemList[current]);
                        // On replace les state des deux objet, celui dans le context et celui passé en parametre à added pour la sauvegarde.
                        if (isAdded)
                        {
                            dbContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Added);
                            collection.CreateSourceQuery().Context.ObjectStateManager.ChangeObjectState(collectionItemList[current], System.Data.EntityState.Added);
                        }
                    }
                    current++;
                }
            }