1

我正在使用 EF4 在数据库中查找一个项目,以确定它是否需要像这样插入或编辑:

 List<Campground> CampgroundEntities = new List<Campground>();

 using (MiscEntities pd = new MiscEntities())
            {
                Campground kc = pd.Campground.FirstOrDefault(i => i.Name == name);

                if (kc != null)
                {
                    kc.StreetAddress = streetAddress;
                    kc.City = city;
                    kc.State = state;
                    kc.Zip = zip;
                    kc.URL = campgroundUrl;
                    kc.UpdatedDT = DateTime.Now;

                    CampgroundEntities.Add(kc);
                }
                else
                {
                    kc = new Campground();
                    kc.Name = name;
                    kc.StreetAddress = streetAddress;
                    kc.City = city;
                    kc.State = state;
                    kc.Zip = zip;
                    kc.URL = campgroundUrl;
                    kc.AddedDateTime = DateTime.Now;

                    CampgroundEntities.Add(kc);
                }
            }

我将我的实体添加到列表中,然后,我想将这些更改提交到数据库:

        using (MiscEntities pd = new MiscEntities())
        {
            foreach (var item in CampgroundEntities)
            {
                pd.Campground.AddObject(item);
            }
            pd.SaveChanges();
        }

现在显然这不起作用,但如果可能的话,我想使用该连接来处理插入和更新。可以做到吗?

4

1 回答 1

1
using (MiscEntities pd = new MiscEntities())
{
    Campground kc = pd.Campground.FirstOrDefault(i => i.Name == name);

    if (kc == null)
    {
        kc = new Campground();
        pd.Campground.Add(kc);          
    }

    kc.StreetAddress = streetAddress;
    kc.City = city;
    kc.State = state;
    kc.Zip = zip;
    kc.URL = campgroundUrl;
    kc.UpdatedDT = DateTime.Now;

    CampgroundEntities.Add(kc);
}
于 2012-06-11T18:53:10.813 回答