6

ProfilePropertyを使用してProfilePropertiesテーブルに を追加しようとしていますObjectContext.AddObject

テーブルのdbフィールドは次のProfilePropertiesとおりです。

ProfilePropertyID
ProfilePropertyDefinitionID
UserID
PropertyValue

テーブルのdbフィールドは次のProfilePropertyDefinitionsとおりです。

ProfilePropertyDefinitionID
PropertyName

渡されるオブジェクトの変数は次のProfilePropertyとおりです。

ProfilePropertyID
ProfilePropertyDefinition
User
PropertyValue

ProfilePropertyDefinitionIDとはUserIDどちらも外部キーであるため、オブジェクトを作成した後、とをテーブルからProfileProperty選択して、 に関連オブジェクトを入力します。UserProfilePropertyDefinitionProfileProperty

次に、AddObjectこれらの変数を含むオブジェクトを渡そうとすると、エラーが発生します。

InnerException = {"値 NULL を列 'PropertyName'、テーブル 'mydbserver.dbo.ProfilePropertyDefinitions' に挿入できません。列は NULL を許可しません。INSERT は失敗します。\r\nステートメントは終了しました。"}

渡したオブジェクトが何を保持しているかを確認するために休憩を取りました。これには次のものがあります。

ProfilePropertyID = -1
ProfilePropertyDefinition = 
    { ProfilePropertyDefinitionID = 3
      PropertyName = "First Name" }
User = /*Not going  to put details here, but assume the user object is there*/
PropertyValue = "Matt"

質問

  1. PropertyNameそこにあるのに null だと言っているのはなぜですか?
  2. そもそもProfilePropertyDefinitionオブジェクトをテーブルに追加しようとしているのはなぜですか? ProfilePropertyDefinitions(関連オブジェクトを追加または更新したくない)

サービス層AddProfile()

public int AddProfile(ProfilePropertyViewModel property)
{
    int objId = -1;
    ProfileProperty profile = null;

    if (ValidateProfile(property))
    {
        try
        {
            using (DbTransaction transaction = _profileRepository.BeginTransaction())
            {
                profile = ProfilePropertyTranslator.ViewToDomain(property);
                profile.User = _userRepository.SelectByKey(UserColumns.UserName, property.UserName);
                profile.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("GraffytysDBEntities.ProfilePropertyDefinition", "ProfilePropertyDefinitionID", property.ProfilePropertyDefinitionID);

                _profileRepository.Add(profile);
                if (_profileRepository.Save() >= 0)
                {
                   transaction.Commit();
                   objId = property.ProfilePropertyId;
                }
            }
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    return objId;
 }

リポジトリAdd():

    public void Add(E entity)
    {
        _ctx.AddObject(entity.GetType().Name, entity);
    }
4

1 に答える 1

6

これはおそらくあなたの問題を解決し、外部キーのプロパティを設定するより効率的な方法です:

profileProperty.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("MyEntities.ProfilePropertyDefinitions", "ProfilePropertyDefinitionID", 3);

「MyEntities」をデータベースモデル名に置き換える必要があります。

コードの他の場所に追加ProfilePropertyDefinitionしているかどうかを確認することもできます。ObjectContextコードのこの部分ではなく、それが問題である可能性があります。

于 2010-01-03T19:21:07.377 に答える