使用EF

时间:2016-01-04 11:09:50

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

您好我在我的asp.net mvc 5 app中使用webAPI。最初我的应用程序在只有货币和用户输入时工作正常,但当我在数据库中添加新表(即CompaniesCompanyCurrencies)与primary & FK relations时,它会抛出异常,如下所示:

  

类型的例外   ' System.Data.Entity.Core.EntityCommandExecutionException'发生在   EntityFramework.SqlServer.dll但未在用户代码中处理

附加信息:执行命令定义时发生错误。

当我将数据从Data Access Layer返回到middle layer时,错误就会出现,如下所示:

private DataAccessLayer db = new DataAccessLayer();
public List<Currency> GetAll()
    {
        return db.Currencies.ToList<Currency>();
    }
我将业务对象链接到db表的

Data access layer如下:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Currency>().ToTable("Currency");
        modelBuilder.Entity<User>().ToTable("Users");
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<CompanyCurrency>().ToTable("CompanyCurrencies");
    }

    public DbSet<Currency> Currencies { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<CompanyCurrency> CompanyCurrencies { get; set; }

型号:

public class Company
{
    [Key]
    [Required]
    public long CompanyCode { get; set; }

    [Required]
    public string CompanyName { get; set; }
    ...
}

public class CompanyCurrency
{
    [Key]
    public long RecordNo { get; set; }
    public long CompanyCode { get; set; }      //I have made it FK in db

    [Required]
    [StringLength(3)]
    [RegularExpression("^[A-Z]{3,3}$")]
    public string CurrencyCode { get; set; }   //and this one also

    public bool IsDefault { get; set; }
}

public class Currency
{
    [Key]
    [Required]
    [StringLength(3)]
    [RegularExpression("^[A-Z]{3,3}$")]
    public string CurrencyCode { get; set; }

    [Required]
    [StringLength(20)]
    public string CurrencyName { get; set; }

    public string MajorUnit { get; set; }

    public string MinorUnit { get; set; }
}
  

我对这个问题的看法是我创建了新表   与主要和外国关键的关系,并有一些方法   在EF中定义这些关系,但我不确切知道什么是   问题是?这只是我的猜测。

所以任何人都可以帮助我,这对我来说是一个很大的帮助。 提前致谢

以下是错误的完整详细信息;

用户代码未处理System.InvalidOperationException   的HResult = -2146233079

  

Message =导航属性CurrencyCode未声明   类型CompanyCurrency上的属性。确认它没有   明确地从模型中排除,并且它是有效的导航   property.Source =的EntityFramework

堆栈跟踪:

    at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociations(EntityType entityType, EdmModel model)
       at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, EdmModel model)
       at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntities(EdmModel model)
       at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(EdmModel model)
       at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at eGLVersion1._0.Data.CurrencyProvider.GetAll() in d:\Laptop Backup\Proglib\eGLVersion1.0\eGLVersion1.0.Data\Providers\CurrencyProvider.cs:line 26
       at eGLVersion1._0.Web.Controllers.CurrencyWebAPIController.Get() in d:\Laptop Backup\Proglib\eGLVersion1.0\eGLVersion1.0.Web\Controllers\CurrencyWebAPIController.cs:line 31
       at lambda_method(Closure , Object , Object[] )
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
  InnerException: 

1 个答案:

答案 0 :(得分:0)

我认为你是对的,这个例外与一些未被定义的关系有关。您可以在类中的属性上通过属性定义关系,或者使用OnModelCreating中的Fluent Api,如

protected override void OnModelCreating(DbModelBuilder modelBuilder){

 modelBuilder.Entity<CompanyCurrency>()
                    .HasForeignKey(companyCurrency => companyCurrency .companyId);

}

请注意,我只输入了伪代码,指向正确的方向。有关更多信息,请查看Relationships and navigation PropertiesEF Fluent API

编辑:对不起@UzairAshraf我的不好,如果你正在使用Ef 6或以上使用HasRequired和HasOptional。由于您使用的是Attribute,因此通过定义虚拟属性,可以更简单地在模型类中执行此操作。

'public class Company
{
    [Key]
    [Required]
    public long CompanyCode { get; set; }

    [Required]
    public string CompanyName { get; set; }
    ...
}'

 public class CompanyCurrency
    {
        [Key]
        public long RecordNo { get; set; }
        public long CompanyCode { get; set; }      //I have made it FK in db
        public virtual Company Company { get; set; }


        [Required]
        [StringLength(3)]
        [RegularExpression("^[A-Z]{3,3}$")]
        public string CurrencyCode { get; set; }   //and this one also

        public bool IsDefault { get; set; }
    }

这将生成表格

CreateTable(
                "dbo.CompanyCurrencies",
                c => new
                    {
                        RecordNo = c.Long(nullable: false, identity: true),
                        CompanyCode = c.Long(nullable: false),
                        CurrencyCode = c.String(nullable: false, maxLength: 3),
                        IsDefault = c.Boolean(nullable: false),
                    })
                .PrimaryKey(t => t.RecordNo)
                .ForeignKey("dbo.Companies", t => t.CompanyCode, cascadeDelete: true)
                .Index(t => t.CompanyCode);