Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试添加它,然后保存上下文?您的用户ID是标识列吗?我会调试整个动态部分。保存前查看数据的最终位置,并检查用户ID。从那里向后走。另外,尝试将User_ID设置为1,而不是0。我的理论是,您的UserID属性被映射为一个标识列(即使这不是您想要的),因此E_C#_Entity Framework_Entity Framework 5 - Fatal编程技术网

C# 尝试添加它,然后保存上下文?您的用户ID是标识列吗?我会调试整个动态部分。保存前查看数据的最终位置,并检查用户ID。从那里向后走。另外,尝试将User_ID设置为1,而不是0。我的理论是,您的UserID属性被映射为一个标识列(即使这不是您想要的),因此E

C# 尝试添加它,然后保存上下文?您的用户ID是标识列吗?我会调试整个动态部分。保存前查看数据的最终位置,并检查用户ID。从那里向后走。另外,尝试将User_ID设置为1,而不是0。我的理论是,您的UserID属性被映射为一个标识列(即使这不是您想要的),因此E,c#,entity-framework,entity-framework-5,C#,Entity Framework,Entity Framework 5,尝试添加它,然后保存上下文?您的用户ID是标识列吗?我会调试整个动态部分。保存前查看数据的最终位置,并检查用户ID。从那里向后走。另外,尝试将User_ID设置为1,而不是0。我的理论是,您的UserID属性被映射为一个标识列(即使这不是您想要的),因此EF查询提供程序认为它不需要插入该值,数据库会抱怨,因为该字段不可为空。出于好奇,为什么要进行所有的动态映射注册?彼得,你是对的。我删除了dbmodelbuilder上的标识映射约定,它工作正常。谢谢这就是问题所在。数据库中只有一条记录,我可以很


尝试添加它,然后保存上下文?您的用户ID是标识列吗?我会调试整个动态部分。保存前查看数据的最终位置,并检查用户ID。从那里向后走。另外,尝试将User_ID设置为1,而不是0。我的理论是,您的UserID属性被映射为一个标识列(即使这不是您想要的),因此EF查询提供程序认为它不需要插入该值,数据库会抱怨,因为该字段不可为空。出于好奇,为什么要进行所有的动态映射注册?彼得,你是对的。我删除了dbmodelbuilder上的标识映射约定,它工作正常。谢谢这就是问题所在。数据库中只有一条记录,我可以很好地读取它。我尝试添加一个新用户,当我保存更改时,它会抛出一个异常。它说用户ID不能为空。我用一条语句创建了表。我确实验证了它不是一个标识列。
public class User : IMappedEntity 
{
    [Key]
    [Column("USER_ID")]
    public int UserID { get; set; }

    [Column("FIRST_NAME")]
    public String FirstName { get; set; }

    [Column("LAST_NAME")]
    public String LastName { get; set; }

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingEntitySetNameConvention>();
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();

    var addMethod = (from m in (modelBuilder.Configurations).GetType().GetMethods()
                     where m.Name == "Add" 
                        && m.GetParameters().Count() == 1
                        && m.GetParameters()[0].ParameterType.Name == typeof(EntityTypeConfiguration<>).Name
                     select m).First();

    if(mappings != null)
    {
        foreach(var map in mappings)
        {
            if(map != null && !mappedTypes.Contains(map.GetType()))
            {
                var thisType = map.GetType();

                if (thisType.IsGenericType)
                {
                    thisType = map.GetType().GenericTypeArguments[0];
                }

                var thisAddMethod = addMethod.MakeGenericMethod(new[] {thisType});
                thisAddMethod.Invoke(modelBuilder.Configurations, new[] { map });
                mappedTypes.Add(map.GetType());
            }
        }
    }
}

private List<Object> BuildMappings(IEnumerable<Type> types)
{
    List<Object> results = new List<Object>();

    var pkType = typeof(KeyAttribute);
    var dbGenType = typeof(DatabaseGeneratedAttribute);

    foreach (Type t in types)
    {
        String tableName = GetTableName(t);
        String schemaName = GetSchema(t);
        var mappingType = typeof(EntityTypeConfiguration<>).MakeGenericType(t);
        dynamic mapping = Activator.CreateInstance(mappingType);

        if (!String.IsNullOrWhiteSpace(schemaName))
           mapping.ToTable(tableName, SchemaName.ToUpper());
        else
           mapping.ToTable(tableName);

        var keys = new List<PropertyInfo>();

        foreach (PropertyInfo prop in t.GetProperties())
        {
            String columnName = prop.Name;

            if(Attribute.IsDefined(prop, typeof(ColumnAttribute)))
            {
                columnName  = (prop.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute).Name;
            }

            if(Attribute.IsDefined(prop, pkType))
               keys.Add(prop);

            var genFunc = (typeof(Func<,>)).MakeGenericType(t, prop.PropertyType);
            var param = Expression.Parameter(t, "t");
            var body = Expression.PropertyOrField(param, prop.Name);
            dynamic lambda = Expression.Lambda(genFunc, body, new ParameterExpression[] { param });

            //if (prop.PropertyType == typeof(Guid) || prop.PropertyType == typeof(Nullable<Guid>))
            //{
            //    mapping.Property(lambda).HasColumnType("Guid");
            //}
            //else
            mapping.Property(lambda).HasColumnName(columnName);

            if (Attribute.IsDefined(prop, dbGenType))
               mapping.Property(lambda).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        }

        if (keys.Count == 0)
           throw new InvalidOperationException("Entity must have a primary key");
        dynamic entKey = null;

        if(keys.Count == 1)
        {
            var genFunc = (typeof(Func<,>)).MakeGenericType(t, keys[0].PropertyType);
            var param = Expression.Parameter(t, "t");
            var body = Expression.PropertyOrField(param, keys[0].Name);
            entKey = Expression.Lambda(genFunc, body, new ParameterExpression[] { param });
        }
        else
        {
            //if entity uses a compound key, it must have a function named "GetPrimaryKey()" which returns Expression<Func<EntityType,Object>>
            //this is because I can't create an expression tree that creates an anonymous type
            entKey = t.GetMethod("GetPrimaryKey");
        }

        mapping.HasKey(entKey);

        results.Add(mapping);
    }

    return results;
}

static void Main(string[] args)
{
    using (var ctx = new DQSA.Data.DBContext("DQSATEST"))
    {
        var xxx = (from u in ctx.Query<DQSA.Data.Entities.User>()
                   select u).ToList(); //this works, I can see my user

        ctx.Set<DQSA.Data.Entities.User>().Add(new DQSA.Data.Entities.User()
            { UserID = 0,
              FirstName="Sam",
              LastName="Sam"
            });

        ctx.SaveChanges(); //get an exception here

        xxx = (from u in ctx.Query<DQSA.Data.Entities.User>()
               select u).ToList();
    }
}
public class User : IMappedEntity 
{
    [Key]
    [Column("USER_ID")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserID { get; set; }

    ...
}
modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();