首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在数据库中获取双倍数据

在数据库中获取双倍数据
EN

Stack Overflow用户
提问于 2018-05-30 03:14:44
回答 1查看 80关注 0票数 0

我从两个数据库中提取学生数据。1个来自可以处理异步调用的在线SOAP API,1个来自具有不支持异步的旧服务的本地数据库。

我比较这些数据库,并通过EF在本地sqlDB中写入差异。

问题:

我的EF数据库中有两个条目。他将正确的数据和数量放在方法内部的数组中,但是看起来一旦他访问了db.savechanges(),他就会跳回几行并再次保存。

我甚至不知道这些额外的帖子是从哪里来的。

在无数次尝试解决它之后,一些代码可能仍然存在。例如,我尝试使用addrange,但当他尝试添加FullVarianceList时,我得到一个错误。

代码语言:javascript
运行
复制
public async Task<bool> FullStudentCompare(string date) //format DD/MM/YYYY
{
    try
    {
        //DB context
        using (var db = new SchoolDbContext())
        {
            //GET DATA
            //SMT (async)
            List<SmtStudent> smtStdudentList = await GetAllSmartschoolStudents();
            //Wisa (sync)
            //on date, or if emty on current systemdate
            List<WisaStudent> wisaList;
            if (date == "")
            {
                wisaList = GetWisaStudentData(DateTime.Now.ToShortDateString());
            }
            else
            {
                wisaList = GetWisaStudentData(date);
            }


            //Flags and props needed for DB entry after compare
            bool existsInLocalDb = false;
            List<Variance> vList = new List<Variance>();
            //Full list to add to DB outside foreach
            List<Variance> fullVarianceList = new List<Variance>();
            //Full List of new Students to write to DB outside foreach
            List<DbStudent> fullStudentList = new List<DbStudent>();

            //Compare lists
            foreach (WisaStudent wstd in wisaList)
            {
                //determine correct classCode
                string klasCode;
                if (wstd.klasgroep.Trim() == "Klasgroep 00")
                {
                    klasCode = wstd.klas.Trim();
                }
                else
                {
                    klasCode = wstd.klasgroep.Trim();
                }


                //Create SmtStudent object for compare
                SmtStudent tempStd = new SmtStudent(true,
                                                    wstd.voornaam.Trim(),
                                                    wstd.naam.Trim(),
                                                    wstd.stamboeknummer.Trim(),
                                                    wstd.geslacht.Trim(),
                                                    wstd.geboortedatum.Trim(),
                                                    wstd.straat.Trim(),
                                                    wstd.huisnummer.Trim(),
                                                    wstd.busnummer.Trim(),
                                                    wstd.postcode.Trim(),
                                                    wstd.gemeente.Trim(),
                                                    wstd.emailadres.Trim(),
                                                    wstd.GSM_nummer.Trim(),
                                                    wstd.levensbeschouwing.Trim(),
                                                    wstd.coaccountmoedervoornaam.Trim(),
                                                    wstd.coaccountmoedernaam.Trim(),
                                                    wstd.coaccountmoederemailadres.Trim(),
                                                    wstd.coaccountmoederGSM_nummer.Trim(),
                                                    wstd.coaccountvadervoornaam.Trim(),
                                                    wstd.coaccountvadernaam.Trim(),
                                                    wstd.coaccountvaderemailadres.Trim(),
                                                    wstd.coaccountvaderGSM_nummer.Trim(),
                                                    klasCode,
                                                    wstd.nationaliteit,
                                                    wstd.geboorteGemeente,
                                                    wstd.geboorteLand
                                                    );


                //Find matching SmtStudent
                SmtStudent smtStd = smtStdudentList.Find(i => i.Internnummer == wstd.stamboeknummer);


                //Find matching Std in local DB
                DbStudent dbStd = await db.Students.Where(i => i.Stamboeknummer == wstd.stamboeknummer).FirstOrDefaultAsync();

                //if none exists in the local DB create an entity to update and write to DB
                if (dbStd == null)
                {
                    dbStd = new DbStudent(wstd.voornaam.Trim(),
                                             wstd.naam.Trim(),
                                             wstd.stamboeknummer.Trim(),
                                             wstd.geslacht.Trim(),
                                             wstd.geboortedatum.Trim(),
                                             wstd.straat.Trim(),
                                             wstd.huisnummer.Trim(),
                                             wstd.busnummer.Trim(),
                                             wstd.postcode.Trim(),
                                             wstd.gemeente.Trim(),
                                             wstd.emailadres.Trim(),
                                             wstd.GSM_nummer.Trim(),
                                             wstd.levensbeschouwing.Trim(),
                                             wstd.coaccountmoedervoornaam.Trim(),
                                             wstd.coaccountmoedernaam.Trim(),
                                             wstd.coaccountmoederemailadres.Trim(),
                                             wstd.coaccountmoederGSM_nummer.Trim(),
                                             wstd.coaccountvadervoornaam.Trim(),
                                             wstd.coaccountvadernaam.Trim(),
                                             wstd.coaccountvaderemailadres.Trim(),
                                             wstd.coaccountvaderGSM_nummer.Trim(),
                                             klasCode,
                                             wstd.loopbaanDatum,
                                             wstd.nationaliteit,
                                             wstd.geboorteGemeente,
                                             wstd.geboorteLand
                                             );

                    db.Students.Add(dbStd);
                    fullStudentList.Add(dbStd);
                }
                else
                {
                    existsInLocalDb = true;
                }

                if (smtStd == null)
                {
                    //Std doesn't exist in Smt -> New student
                    dbStd.IsNewStudent = true;
                    dbStd.ClassMovement = true;

                    //remove from wisaList
                    wisaList.Remove(wstd);
                }
                else
                {
                    //clear vlist from previous iterations
                    vList.Clear();

                    //get all properties on the obj, cycle through them and find differences
                    PropertyInfo[] props = smtStd.GetType().GetProperties();

                    vList.AddRange(props.Select(f => new Variance
                    {
                        Property = f.Name,
                        ValueA = f.GetValue(smtStd),
                        ValueB = f.GetValue(tempStd),
                        Checked = false
                    })
                       .Where(v => !v.ValueA.Equals(v.ValueB) && v.ValueB != null)
                       .ToList());


                    //If the users allrdy exists in LocalDb delete all previously recorded variances
                    if (existsInLocalDb)
                    {
                        if (db.Variances.Where(j => j.Student.StudentId.Equals(dbStd.StudentId)).FirstOrDefault() != null)
                        {                            //if the student allready exists we will recreate the variancelist, hence deleting all current items first
                            List<Variance> existingList = db.Variances.Where(j => j.Student.StudentId.Equals(dbStd.StudentId)).ToList();
                            foreach (Variance v in existingList)
                            {
                                db.Variances.Remove(v);
                            }
                        }
                    }

                    //Add new variances if vList is not empty
                    if (vList.Count > 0)
                    {
                        //Check if KlasCode is a variance -> set classmovement to true
                        if (vList.Where(i => i.Property == "KlasCode").FirstOrDefault() != null)
                        {
                            dbStd.ClassMovement = true;
                        }
                        else
                        {
                            dbStd.ClassMovement = false;
                        }

                        //add the StudentObject to the variance to link them 1-many
                        foreach (Variance v in vList)
                        {
                            v.Student = dbStd;
                            fullVarianceList.Add(v);
                            db.Variances.Add(v);
                        }
                    }
                }
            }

            //add the full lists of variances and new students to DB
            //db.Variances.AddRange(fullVarianceList);
            //db.Students.AddRange(fullStudentList);

            db.SaveChanges();

            return true;
        }
    }
    catch(Exception ex)
    {
        return false;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-05-30 03:34:10

有几件事:

  1. 理解EF使用工作单元模式很重要,在这种模式中,对实体的任何更改都不会持久,直到调用SaveChanges,这解释了“一旦他命中db.Savechanges(),他就会跳回”现象。
  2. 如果您有一对多的关系,并且您将一个实体集合分配给另一个实体上的导航属性,然后将该父实体添加到DbContext中,EF会将这些子实体也标记为要添加。在本例中,dbStd被添加到"db.Students.Add(dbStd);“行和"v.Student = dbStd;”行。这很可能是导致重复项的原因。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50591409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档