0

私はEF4.0を使用してDALクラスを書いています、私は読んだ

http://www.codeproject.com/Articles/43367/ADO-NET-Entity-Framework-as-Data-Access-Layer

http://msdn.microsoft.com/en-us/magazine/cc700340.aspx

しかし、彼らのコードをテストすると、UpdateandDeleteメソッドでいくつかの問題が発生します。

DALクラスのすべてのコードは次のとおりです。

public class FriendlinkDA : IDisposable
{
    private EdiBlogEntities context;

    public FriendlinkDA()
    {
        context = new EdiBlogEntities();
    }

    public void Dispose()
    {
        context.Dispose();
    }

    public FriendLink GetFriendLink(Guid id)
    {
        return context.FriendLink.FirstOrDefault(f => f.Id == id);
    }

    public void Update(FriendLink model)
    {
        // Way 1:  (throw exception)
        //context.Attach(model);
        //model.SetAllModified(context);
        //context.SaveChanges();

        // Way 2: 
        EntityKey key;
        object originalItem;
        key = context.CreateEntityKey("FriendLink", model);
        if (context.TryGetObjectByKey(key, out originalItem))
        {
            context.ApplyCurrentValues(key.EntitySetName, model);
            //context.ApplyPropertyChanges(key.EntitySetName, model);
        }
        context.SaveChanges();
    }

    public void Delete(FriendLink model)
    {
        // Way 1:
        context.Attach(model);
        context.DeleteObject(model);
        context.SaveChanges();

        // Way 2:
        //var item = context.FriendLink.FirstOrDefault(f => f.Id == model.Id);
        //context.DeleteObject(item);
        //context.SaveChanges();
    }
}

拡張方法は次のとおりです。

public static void SetAllModified<T>(this T entity, ObjectContext context) where T : IEntityWithKey
{
    var stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey);
    var propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select
      (pn => pn.FieldType.Name);
    foreach (var propName in propertyNameList)
        stateEntry.SetModifiedProperty(propName);
}

アプリケーションでは、次のようにDALを使用しています。

// Delete
using (var optFriendlink = new FriendlinkDA())
{
    var test = optFriendlink.GetFriendLink(new Guid("81F58198-D396-41DE-A240-FC306C7343E8"));
    optFriendlink.Delete(test);
}

// Update
using (var optFriendlink = new FriendlinkDA())
{
    var testLink = optFriendlink.GetFriendLink(new Guid("62FD0ACF-40C3-4BAD-B438-38BB540A6080"));
    testLink.Title = "ABC";
    optFriendlink.Update(testLink);
}

質問1:

Delete()では、方法1と方法2の両方が機能します。どちらがいいですか?

質問2:

Update()で、方法1で例外が発生します。オブジェクトは既にオブジェクトコンテキストにあるため、オブジェクトをアタッチできません。オブジェクトは、変更されていない状態の場合にのみ再アタッチできます。

このステートメントについて:context.Attach(model);

しかし、方法2は問題ありません。

なぜこうなった?Delete()でもモデルをアタッチしますが、Delete()が正常に機能するのはなぜですか?更新を正しく書き込むにはどうすればよいですか?

4

1 に答える 1

1

例外はそれをすべて言います:

オブジェクトは、変更されていない状態の場合にのみ再アタッチできます。

の下のコードスニペットでオブジェクトを変更した// Updateため、再アタッチできません。

どちらの方法が良いかについて。通常、コンテキストからオブジェクトを取得し、コンテキストを破棄し、オブジェクトで何かを実行してから、新しいコンテキストを使用してオブジェクトを保存します。その場合Attach、最初にIdでオブジェクトを取得するよりも、使用する方がはるかに快適です。

于 2012-08-16T21:00:26.940 に答える