防止重复数据库被保存在数据库中

时间:2015-12-21 15:21:31

标签: c# entity-framework linq

我已经制作了一个使用Entity Framework保存数据的控制台应用程序,我有一个像这样设计的表:

ID     People_ID   People_Address    People_Postcode
---    ----------  --------------    ----------------
1       2          76 Nation Road     B27 8NT
2       7          88 Grimestone Road B45 9WG
3       12         45 Wallock Road    B22 4UI

为了确保副本不存储在表中,已编写以下代码:

ppl.People_Address = Address;
ppl.People_Postcode = Postcode;
ppl.People_ID = usr.ID;


If(db.tbl_people.Any(x=> x.people_address != ppl.People_Address) && (db.tbl_people.Any(x=> x.people_postcode != ppl.People_Postcode) &&  (db.tbl_people.Any(x=> x.People_ID != ppl.People_ID) {

db.tbl_people.Add(ppl)
db.SaveChanges();
}

然而,无论是否存在表中没有任何内容可以添加任何内容,任何帮助?

3 个答案:

答案 0 :(得分:1)

如果您的字段为null,则需要检查每个字段。例如:

x.people_address != ppl.People_Address || x.people_adress == null

答案 1 :(得分:0)

此代码存在一些问题。

首先,每次调用时不应该多次导致数据库" db.tbl_people"财产吸气剂。做一次,不要检索整个数据库集合。

其次,对于空数据库

db.tbl_people.Any(x=> x.people_address != ppl.People_Address)

返回false,因为tbl_people集合中没有实体。

第三个条件并不是真正检查数据库中的重复项。

您的查询可能如下所示:

// if there is no entities with same properties
if(db.tbl_people.Count(p => p.people_address == ppl.People_Address 
                         && p.people_postcode == ppl.People_postcode 
                         && p.People_ID == ppl.People_ID) == 0)
{
    // then save new entity
    db.tbl_people.Add(ppl)
    db.SaveChanges();
}

此代码将生成对数据库的查询,该查询将仅返回标量变量,并且它将更好地用于性能和通信通道。

答案 2 :(得分:0)

问题是条件

if (db.tbl_people.Any(x=> x.people_address != ppl.People_Address)
    && (db.tbl_people.Any(x=> x.people_postcode != ppl.People_Postcode)
    && (db.tbl_people.Any(x=> x.People_ID != ppl.People_ID)

它应该是

if (!db.tbl_People.Any(x => x.people_address == ppl.People_Address
    && x.people_postcode == ppl.People_Postcode
    && x.People_ID == ppl.People_ID))
{
    // No duplicate
}