EntityFramework,如果不存在则插入,否则更新 [英] EntityFramework, Insert if not exist, otherwise update

查看:136
本文介绍了EntityFramework,如果不存在则插入,否则更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Entity-Set国家,在我的数据库中反映了数据库表'<'char(2),char(3),nvarchar(50>)。

I'm having a Entity-Set Countries, reflecting a database table '<'char(2),char(3),nvarchar(50> in my database.

我有一个解析器,它返回一个已解析国家的Country []数组,并且在以正确的方式更新它时遇到了问题。我想要的是:以国家数组为例,对于那些尚未在数据库中的国家插入它们,

Im having a parser that returns a Country[] array of parsed countries, and is having issues with getting it updated in the right way. What i want is: Take the array of countries, for those countries not already in the database insert them, and those existing update if any fields is different. How can this be done?

void Method(object sender, DocumentLoadedEvent e)
{
    var data = e.ParsedData as Country[];
    using(var db = new DataContractEntities)
    {
       //Code missing

    
    }
}

我在想类似的东西

for(var c in data.Except(db.Countries)) but it wount work as it compares on wronge fields.

希望任何人以前都遇到过这个问题,并且对我有解决方案。如果我不能使用Country对象并且我nsert /更新它们的数组很容易,我看不到使用框架有什么好处,因为从表演者那里我认为编写自定义的sql脚本以插入它们而不是在插入之前检查某个国家是否已经在数据库中会更快。

Hope anyone have had this issues before, and have a solution for me. If i cant use the Country object and insert/update an array of them easy, i dont see much benefict of using the framework, as from performers i think its faster to write a custom sql script that inserts them instead of ect checking if an country is already in the database before inserting?

我添加了覆盖等于我所在国家/地区类别的内容:

I added override equals to my country class:

    public partial class Country
{
    
    public override bool Equals(object obj)
    {
        if (obj is Country)
        {
            var country = obj as Country;
            return this.CountryTreeLetter.Equals(country.CountryTreeLetter);
        }
        return false;
    }
    public override int GetHashCode()
    {
        int hash = 13;
        hash = hash * 7 + (int)CountryTreeLetter[0];
        hash = hash * 7 + (int)CountryTreeLetter[1];
        hash = hash * 7 + (int)CountryTreeLetter[2];
        return hash;
    }
}

然后执行:

        var data = e.ParsedData as Country[];
        using (var db = new entities())
        {
            foreach (var item in data.Except(db.Countries))
            {
                db.AddToCountries(item); 
            }
            db.SaveChanges();
        }


推荐答案

我会简单地做到这一点:

I would do it straightforward:

void Method(object sender, DocumentLoadedEvent e)
{
    var data = e.ParsedData as Country[];
    using(var db = new DataContractEntities)
    {
        foreach(var country in data)
        {
            var countryInDb = db.Countries
                .Where(c => c.Name == country.Name) // or whatever your key is
                .SingleOrDefault();
            if (countryInDb != null)
                db.Countries.ApplyCurrentValues(country);
            else
                db.Countries.AddObject(country);
        }
        db.SaveChanges();
     }
}

我不知道您的应用程序必须运行的频率这个世界或您拥有多少个国家。但是我有种感觉,您不必考虑复杂的性能优化。

I don't know how often your application must run this or how many countries your world has. But I have the feeling that this is nothing where you must think about sophisticated performance optimizations.

编辑

仅发出一个查询的替代方法:

Alternative approach which would issue only one query:

void Method(object sender, DocumentLoadedEvent e)
{
    var data = e.ParsedData as Country[];
    using(var db = new DataContractEntities)
    {
        var names = data.Select(c => c.Name);
        var countriesInDb = db.Countries
            .Where(c => names.Contains(c.Name))
            .ToList(); // single DB query
        foreach(var country in data)
        {
            var countryInDb = countriesInDb
                .SingleOrDefault(c => c.Name == country.Name); // runs in memory
            if (countryInDb != null)
                db.Countries.ApplyCurrentValues(country);
            else
                db.Countries.AddObject(country);
        }
        db.SaveChanges();
     }
}

这篇关于EntityFramework,如果不存在则插入,否则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆