我有一个现有的数据库,其PK是一个数字(18,0),一个FK是一个int。当我尝试使用导航属性时,EF会抛出一个无效的强制转换异常。
有没有办法映射这种关系,以解决无效的演员?
在下面的代码中,promo_cfg.pc_id是数字(18,0),promo.pc_id是int。
public class PromotionMap : EntityTypeConfiguration<Promotion>
{
public PromotionMap()
{
// Primary Key
this.HasKey(p => p.PromotionId);
// Properties
// table and column mappings
this.ToTable("promo");
this.Property(p => p.PromotionId).HasColumnName("p_id");
this.Property(p => p.PromotionConfigId).HasColumnName("pc_id");
this.Property(p => p.PromotionCode).HasColumnName("p_code");
this.HasRequired(t => t.PromotionConfig)
.WithMany(t => t.Promotions)
.HasForeignKey(d => new { d.PromotionConfigId });
}
}
public class Promotion
{
public decimal PromotionId { get; set; }
public int PromotionConfigId { get; set; }
public string PromotionCode { get; set; }
}
public PromotionConfigMap()
{
// Primary Key
this.HasKey(s => s.PromotionConfigId);
// Properties
// Table and Column mappings
this.ToTable("promo_cfg");
this.Property(p => p.PromotionConfigId).HasColumnName("pc_id");
this.Property(p => p.AllowOrders).HasColumnName("allow_orders");
this.HasOptional(p => p.Promotions).WithRequired().Map(x => x.MapKey("pc_id"));
}
public class PromotionConfig
{
public int PromotionConfigId { get; set; }
public int AllowOrders { get; set; }
public virtual ICollection<Promotion> Promotions { get; set; }
}
答案 0 :(得分:0)
可能是一个大的MAY,有一个非物化的FK:
HasOptional(x => x.SomeProperty).WithMany().Map(x => x.MapKey("intDbColumnName"));
=============================================== =========
我删除了所有不需要的代码,以下内容应该:
public class Promotion
{
public decimal PromotionId { get; set; }
//Here you do not materialize the FK
public PromotionConfig PromotionConfig { get; set; }
}
public class PromotionConfig
{
public decimal PromotionConfigId { get; set; } // you can't do otherwise as
//you must declare a PK for EF
public virtual ICollection<Promotion> Promotions { get; set; }
}
public class PromotionMap : EntityTypeConfiguration<Promotion>
{
public PromotionMap()
{
// Primary Key
this.HasKey(p => p.PromotionId);
// Properties
// table and column mappings
this.ToTable("promo");
this.Property(p => p.PromotionId).HasColumnName("p_id");
//if I well understand pc_id is an int that relates to a decimal
this.HasRequired(p => p.PromotionConfig)
.WithMany(pc => pc.Promotions)
.Map(p => p.MapKey("pc_id"));
}
}
public class PromotionConfigMap : EntityTypeConfiguration<PromotionConfig> {
public PromotionConfigMap()
{
// Primary Key
this.HasKey(s => s.PromotionConfigId);
// Properties
// Table and Column mappings
this.ToTable("promo_cfg");
}
}