有实体框架的麻烦

Mat*_*att 6 .net c# asp.net-mvc entity-framework mef

我正在尝试使用添加ProfilePropertyProfileProperties表中ObjectContext.AddObject.

该表的db字段ProfileProperties是:

ProfilePropertyID
ProfilePropertyDefinitionID
UserID
PropertyValue
Run Code Online (Sandbox Code Playgroud)

该表的db字段ProfilePropertyDefinitions是:

ProfilePropertyDefinitionID
PropertyName
Run Code Online (Sandbox Code Playgroud)

ProfileProperty传入的对象的变量是:

ProfilePropertyID
ProfilePropertyDefinition
User
PropertyValue
Run Code Online (Sandbox Code Playgroud)

ProfilePropertyDefinitionIDUserID两个外键,所以在创建后ProfileProperty的对象我选择了UserProfilePropertyDefinition从他们的桌子,以填补ProfileProperty与相关对象.

然后,当我尝试AddObject,传入一个带有这些变量的对象时,我收到一个错误:

InnerException = {"无法将值NULL插入列'PropertyName',表'mydbserver.dbo.ProfilePropertyDefinitions';列不允许空值.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"
Run Code Online (Sandbox Code Playgroud)

问题

  1. 为什么说它在PropertyName那里是空的?
  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;
 }
Run Code Online (Sandbox Code Playgroud)

存储库Add():

    public void Add(E entity)
    {
        _ctx.AddObject(entity.GetType().Name, entity);
    }
Run Code Online (Sandbox Code Playgroud)

Luk*_*Led 6

这将解决您的问题,并且是设置外键属性的更有效方法:

profileProperty.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("MyEntities.ProfilePropertyDefinitions", "ProfilePropertyDefinitionID", 3);
Run Code Online (Sandbox Code Playgroud)

您必须将"MyEntities"替换为您的数据库模型名称.

您还可以检查是否要添加ProfilePropertyDefinitionObjectContext代码中的其他位置.这可能是问题,而不是代码的这一部分.