无效的列名称或Identity_Insert关闭

时间:2014-02-18 20:50:19

标签: c# asp.net-mvc entity-framework-4

我整个上午都在和CF EF一起巡游。我想我已经解决了所有问题,但我确定这个问题是由于我缺乏知识/理解。

问题集中在一个表和所述表的映射,所以我先给出定义,然后解释问题。以下是表的定义方式:

enter image description here

现在我将类表示定义为:

public partial class ExternalForumCredentials : BaseEntity
{
   public virtual int Customer_Id { get; set; }
   public virtual int ExternalForumBoardId { get; set; }
   public virtual string Username { get; set; }
   public virtual string Password { get; set; }
 }

和映射:

public ExternalForumCredentialsMap()
{
   this.ToTable("ExternalForumCredentials");
   this.HasKey(ef => ef.Id);
   this.HasKey(ef => ef.Customer_Id);
   this.HasKey(ef => ef.ExternalForumBoardId);
   this.Property(ef => ef.Username).IsRequired().HasMaxLength(100);
   this.Property(ef => ef.Password).IsRequired().HasMaxLength(100);

 }

现在我没有显示控制器代码,因为我认为问题出在我的ef配置中。但是,如果我错了,只需告诉我需要添加的内容,我会立即这样做。

所以......鉴于ID,Customer_Id和ExternalForumBoardId是主键,我定义了如上所示的映射。

使用这种配置一切顺利到插入...然后它崩溃说我正在尝试做IDENTITY_INSERT。好的,因为我在控制器中为Customer_Id和ExternalForumBoardId赋值,并且因为映射将它们作为键存在冲突,所以这是有意义的。

所以我将映射更改为:

public ExternalForumCredentialsMap()
{
        this.ToTable("ExternalForumCredentials");
        this.HasKey(ef => ef.Id);
        this.Property(ef => ef.Customer_Id);
        this.Property(ef => ef.ExternalForumBoardId);
        this.Property(ef => ef.Username).IsRequired().HasMaxLength(100);
        this.Property(ef => ef.Password).IsRequired().HasMaxLength(100);       
}

在我甚至可以执行插入操作之前,我收到一个错误:列名称Customer_Id无效,当然我的知识有限,我不明白,因为我已经定义了Customer_Id。

我也在映射中尝试了HasRequired,但是甚至不会编译说“int类型必须是引用类型才能将它用作参数......”

其他映射选项(例如Ignore)在此上下文中似乎没有意义。

任何帮助解释我做错了什么都会非常感激。


Db上下文接口:

public interface IDbContext 
{
    IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;

    int SaveChanges();

    IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters)
        where TEntity : BaseEntity, new();

    /// <summary>
    /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
    /// </summary>
    /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
    /// <param name="sql">The SQL query string.</param>
    /// <param name="parameters">The parameters to apply to the SQL query string.</param>
    /// <returns>Result</returns>
    IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters);

    /// <summary>
    /// Executes the given DDL/DML command against the database.
    /// </summary>
    /// <param name="sql">The command string</param>
    /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
    /// <param name="parameters">The parameters to apply to the command string.</param>
    /// <returns>The result returned by the database after executing the command.</returns>
    int ExecuteSqlCommand(string sql, int? timeout = null, params object[] parameters);
   }
}

public static class DbContextExtensions {
    /// <summary>
    /// Loads the database copy.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="context">The context.</param>
    /// <param name="currentCopy">The current copy.</param>
    /// <returns></returns>
    public static T LoadDatabaseCopy<T>(this IDbContext context, T currentCopy) where T : BaseEntity {
        return InnerGetCopy(context, currentCopy, e => e.GetDatabaseValues());
    }

    private static T InnerGetCopy<T>(IDbContext context, T currentCopy, Func<DbEntityEntry<T>, DbPropertyValues> func) where T : BaseEntity {
        //Get the database context
        DbContext dbContext = CastOrThrow(context);

        //Get the entity tracking object
        DbEntityEntry<T> entry = GetEntityOrReturnNull(currentCopy, dbContext);

        //The output 
        T output = null;

        //Try and get the values
        if (entry != null) {
            DbPropertyValues dbPropertyValues = func(entry);
            if(dbPropertyValues != null) {
                output = dbPropertyValues.ToObject() as T;
            }
        }

        return output;
    }

    /// <summary>
    /// Gets the entity or return null.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="currentCopy">The current copy.</param>
    /// <param name="dbContext">The db context.</param>
    /// <returns></returns>
    private static DbEntityEntry<T> GetEntityOrReturnNull<T>(T currentCopy, DbContext dbContext) where T : BaseEntity {
        return dbContext.ChangeTracker.Entries<T>().Where(e => e.Entity == currentCopy).FirstOrDefault();
    }

    private static DbContext CastOrThrow(IDbContext context) {
        DbContext output = (context as DbContext);

        if(output == null) {
            throw new InvalidOperationException("Context does not support operation.");
        }

        return output;
    }

    /// <summary>
    /// Loads the original copy.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="context">The context.</param>
    /// <param name="currentCopy">The current copy.</param>
    /// <returns></returns>
    public static T LoadOriginalCopy<T>(this IDbContext context, T currentCopy) where T : BaseEntity {
        return InnerGetCopy(context, currentCopy, e => e.OriginalValues);
    }
}

和实施:

public class ObjectContext : DbContext, IDbContext
{
    public ObjectContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
        //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //dynamically load all configuration
        System.Type configType = typeof(LanguageMap);   //any of your configuration classes here
        var typesToRegister = Assembly.GetAssembly(configType).GetTypes()
        .Where(type => !String.IsNullOrEmpty(type.Namespace))
        .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
        foreach (var type in typesToRegister)
        {
            dynamic configurationInstance = Activator.CreateInstance(type);
            modelBuilder.Configurations.Add(configurationInstance);
        }
        //...or do it manually below. For example,
        //modelBuilder.Configurations.Add(new LanguageMap());



        base.OnModelCreating(modelBuilder);
    }

    /// <summary>
    /// Attach an entity to the context or return an already attached entity (if it was already attached)
    /// </summary>
    /// <typeparam name="TEntity">TEntity</typeparam>
    /// <param name="entity">Entity</param>
    /// <returns>Attached entity</returns>
    protected virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
    {
        //little hack here until Entity Framework really supports stored procedures
        //otherwise, navigation properties of loaded entities are not loaded until an entity is attached to the context
        var alreadyAttached = Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault();
        if (alreadyAttached == null)
        {
            //attach new entity
            Set<TEntity>().Attach(entity);
            return entity;
        }
        else
        {
            //entity is already loaded.
            return alreadyAttached;
        }
    }

    public string CreateDatabaseScript()
    {
        return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
    }

    public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
    {
        return base.Set<TEntity>();
    }

    public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
    {
        //HACK: Entity Framework Code First doesn't support doesn't support output parameters
        //That's why we have to manually create command and execute it.
        //just wait until EF Code First starts support them
        //
        //More info: http://weblogs.asp.net/dwahlin/archive/2011/09/23/using-entity-framework-code-first-with-stored-procedures-that-have-output-parameters.aspx

        bool hasOutputParameters = false;
        if (parameters != null)
        {
            foreach (var p in parameters)
            {
                var outputP = p as DbParameter;
                if (outputP == null)
                    continue;

                if (outputP.Direction == ParameterDirection.InputOutput ||
                    outputP.Direction == ParameterDirection.Output)
                    hasOutputParameters = true;
            }
        }



        var context = ((IObjectContextAdapter)(this)).ObjectContext;
        if (!hasOutputParameters)
        {
            //no output parameters
            var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList();
            for (int i = 0; i < result.Count; i++)
                result[i] = AttachEntityToContext(result[i]);

            return result;

            //var result = context.ExecuteStoreQuery<TEntity>(commandText, parameters).ToList();
            //foreach (var entity in result)
            //    Set<TEntity>().Attach(entity);
            //return result;
        }
        else
        {

            //var connection = context.Connection;
            var connection = this.Database.Connection;
            //Don't close the connection after command execution


            //open the connection for use
            if (connection.State == ConnectionState.Closed)
                connection.Open();
            //create a command object
            using (var cmd = connection.CreateCommand())
            {
                //command to execute
                cmd.CommandText = commandText;
                cmd.CommandType = CommandType.StoredProcedure;

                // move parameters to command object
                if (parameters != null)
                    foreach (var p in parameters)
                        cmd.Parameters.Add(p);

                //database call
                var reader = cmd.ExecuteReader();
                //return reader.DataReaderToObjectList<TEntity>();
                var result = context.Translate<TEntity>(reader).ToList();
                for (int i = 0; i < result.Count; i++)
                    result[i] = AttachEntityToContext(result[i]);
                //close up the reader, we're done saving results
                reader.Close();
                return result;
            }

        }
    }

    /// <summary>
    /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
    /// </summary>
    /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
    /// <param name="sql">The SQL query string.</param>
    /// <param name="parameters">The parameters to apply to the SQL query string.</param>
    /// <returns>Result</returns>
    public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
    {
        return this.Database.SqlQuery<TElement>(sql, parameters);
    }

    /// <summary>
    /// Executes the given DDL/DML command against the database.
    /// </summary>
    /// <param name="sql">The command string</param>
    /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
    /// <param name="parameters">The parameters to apply to the command string.</param>
    /// <returns>The result returned by the database after executing the command.</returns>
    public int ExecuteSqlCommand(string sql, int? timeout = null, params object[] parameters)
    {
        int? previousTimeout = null;
        if (timeout.HasValue)
        {
            //store previous timeout
            previousTimeout = ((IObjectContextAdapter) this).ObjectContext.CommandTimeout;
            ((IObjectContextAdapter) this).ObjectContext.CommandTimeout = timeout;
        }

        var result = this.Database.ExecuteSqlCommand(sql, parameters);

        if (timeout.HasValue)
        {
            //Set previous timeout back
            ((IObjectContextAdapter) this).ObjectContext.CommandTimeout = previousTimeout;
        }

        //return result
        return result;
    }
}

1 个答案:

答案 0 :(得分:1)

您有另一个与ExternalForumCredentials有关系但没有正确配置的类。 EntityFramework将尽力猜测您的约定,因此它猜测它可以连接到Customer_Id

转到使用ExternalForumCredentials的任何地图并正确配置它们。例如:

this.HasMany(ef => ef.ExternalForumCredentials)
    .WithRequired()
    .HasForeignKey(ef => ef.Customer_Id);