更新实体框架中现有的 EntityCollection

发布于 2024-09-29 05:18:07 字数 1509 浏览 3 评论 0原文

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

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;
    }
}

我尝试保存我的专家实体并且它正在工作,但我不知道如何将我的 EntityCollection 保存在我的专家实体中。有人可以帮助我吗?

I try to work with link to entity, and i want to work directly with my entity in my application.

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;
    }
}

I try to save my expert entity and it's working, but i dont know how to save my EntityCollection in my expert Entity. some body can help me ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江南月 2024-10-06 05:18:07

尝试摆脱其他:

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;
    }
}

Try get rid of the else:

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;
    }
}
在巴黎塔顶看东京樱花 2024-10-06 05:18:07

好吧,我找到了如何更新我的实体集合。

这里面有我的技术。我没有找到任何有关该技术的文档,所以请给我您的反馈

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++;
            }
        }

Ok i found how i could update my entity collection.

There is my technique. I did not find any documentation on the technique, so give me your feed back

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++;
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文