实体框架代码首先使用T4模板



我将使用T4模板创建代码优先视图,如下文所述:

文章在这里

但它导致

运行时异常

如下。为什么?

我的连接字符串在App.config中配置正确。

我的应用程序是基于N-Tier的。因此DbContext驱动的类在数据层中。

这是我的连接字符串

<add name="PawLoyalty" connectionString="Server=.;database=PawLoyalty;Trusted_connection=true;pooling=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

与2010年相比,我使用EF 4.1。

正在运行转换:System.Reflection.TargetInvocationException:已引发异常通过调用的目标
--->System.ArgumentException:参数"nameOrConnectionString"不能为null、空或仅包含空格

在System.Data.Entity.ModelConfiguration.Utilities.RuntimeFailureMethods.ReportFailure(ContractFailureKind-ContractFailureKind,字符串userMessage,字符串conditionText,异常innerException)
在D:\My Blog\Test中的System.Data.Entity.DbContext.ctor(字符串名称或连接字符串)
PawLoyalty.Data.DataCatalog.ctor(布尔allowLazyLoading)Projects\PawLoyalty\PawLoyalty\Data\DataCatalog.cs:line31
在D:\My Blog\DestProjects\Paw Loyalty \PawLoyalty.Data\DataCatalog.cs:line 26
---内部异常堆栈跟踪结束---
位于System.RuntimeTypeHandle.CreateInstance(RuntimeType类型,布尔publicOnly,布尔noCheck,布尔&canBeCached,RuntimeMethodHandleInternal&ctor,布尔&bNeedSecurityCheck)
System.RuntimeType.CreateInstanceSlow(布尔publicOnly,布尔skipCheckThis,布尔fillCache,StackCrawlMark&stackMark)
在System.RuntimeType.CreateInstanceDefaultCtor(布尔publicOnly,布尔skipCheckThis;stackMark)
在System.Activator.CreateInstance(类型类型,布尔非公共)
Microsoft.VisualStudio.TextTemplateD6E95B37BD0790EBBCC7DB570AD3E2AC.GeneratedTextTransformation.GetEdmx(类型contextType)
在Microsoft.VisualStudio.TextTemplateD6E95B37BD0790EBBCC7DB570AD3E2AC.GeneratedTextTransformation.GenerateViews(String contextTypeName)
在Microsoft.VisualStudio.textTemplateD6E95B 37BD0790ebBCC7DB570 AD3E2AC.GenerateTextTransformation.TransformText()会话,字符串源,ITextTemplateingEngineHost主机,String&结果)

更新

我的DbContext派生类如下所示。

[Export(typeof(ISecurityDataCatalog))]
[Export(typeof(IMappingDataCatalog))]
[Export(typeof(IPawLoyaltyDataCatalog))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class DataCatalog : DbContext, IPawLoyaltyDataCatalog, ISecurityDataCatalog, IMappingDataCatalog
{
public static string ConnectionString { get; set; }
public static string AccountToken { get; set; }
public DataCatalog()
: this(false)
{
}
public DataCatalog(bool allowLazyLoading = false)
: base(ConnectionString)
{
Configuration.LazyLoadingEnabled = allowLazyLoading;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<DiscountValue>().Property(d => d.Fixed).HasPrecision(18, 2);
modelBuilder.ComplexType<DiscountValue>().Property(d => d.Percentage).HasPrecision(18, 4);
modelBuilder.Entity<InvoiceFee>().Property(d => d.Fixed).HasPrecision(18, 2);
modelBuilder.Entity<InvoiceFee>().Property(d => d.Percentage).HasPrecision(18, 4);
modelBuilder.Entity<InvoiceFee>().Property(d => d.Total).HasPrecision(18, 4);
modelBuilder.Entity<Invoice>().Property(d => d.Discount).HasPrecision(18, 2);
modelBuilder.Entity<Invoice>().HasRequired(i => i.Appointment).WithOptional(a => a.Invoice).WillCascadeOnDelete(false);
modelBuilder.Entity<InvoiceItem>().Property(d => d.Price).HasPrecision(18, 2);
modelBuilder.Entity<InvoiceItem>().Property(d => d.LatestTotal).HasPrecision(18, 2);
modelBuilder.Entity<InvoiceItem>().HasRequired(i => i.Allocation).WithOptional(a => a.InvoiceItem).WillCascadeOnDelete(false);
modelBuilder.Entity<InvoicePayment>().Property(d => d.Amount).HasPrecision(18, 4);
modelBuilder.Entity<ServicePrice>().Property(d => d.Price).HasPrecision(18, 2);
modelBuilder.Entity<ServiceBreedPrice>().Property(d => d.Price).HasPrecision(18, 2);
modelBuilder.Entity<ProviderPolicy>().Property(d => d.SalesTax).HasPrecision(18, 4);
modelBuilder.Entity<ProviderCredit>().Property(d => d.Balance).HasPrecision(18, 2);
modelBuilder.Entity<CombinedServiceDiscountDefinition>().HasRequired(c => c.PrimaryService).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<CombinedServiceDiscountDefinition>().HasRequired(c => c.SecondaryService).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<MedicalRecord>().HasRequired(m => m.Pet).WithOptional(p => p.Medical).WillCascadeOnDelete(false);
modelBuilder.Entity<BehavioralRecord>().HasRequired(b => b.Pet).WithOptional(p => p.Behavioral).WillCascadeOnDelete(false);
modelBuilder.Entity<DietRecord>().HasRequired(d => d.Pet).WithOptional(p => p.Diet).WillCascadeOnDelete(false);
modelBuilder.Entity<Provider>().HasOptional(p => p.Profile).WithRequired(p => p.Provider).WillCascadeOnDelete(true);
modelBuilder.Entity<ProviderProfile>().HasOptional(p => p.Policy).WithRequired(p => p.Profile).WillCascadeOnDelete(true);
modelBuilder.Entity<ProviderProfile>().HasOptional(p => p.CustomerRequirements).WithRequired(p => p.Profile).WillCascadeOnDelete(true);
modelBuilder.Entity<ProviderProfile>().HasOptional(p => p.PaymentProfile).WithRequired(p => p.Profile).WillCascadeOnDelete(true);
modelBuilder.Entity<Resource>().HasMany(r => r.Availability).WithRequired(a => a.Resource).WillCascadeOnDelete(true);
Database.SetInitializer<DataCatalog>(null);
base.OnModelCreating(modelBuilder);
}
public const string ServiceKey = "PawLoyalty";
public DbSet<StreetAddress> StreetAddresses { get; set; }
public DbSet<Appointment> Appointments { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InsuranceCarrier> InsuranceCarriers { get; set; }
public DbSet<PromotionCode> PromotionCodes { get; set; }
// Provider Classes
public DbSet<Provider> Providers { get; set; }
public DbSet<ProviderProfile> ProviderProfiles { get; set; }
//public DbSet<ProviderResourceItem> ProviderResourceItems { get; set; }
public DbSet<Allocation> ResourceAllocations { get; set; }
public DbSet<ResourceAvailability> ResourceAvailabilities { get; set; }
public DbSet<Resource> Resources { get; set; }
/// <summary>
/// Wraps the object context detach method
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void Detach<T>(T t) where T : class
{
// TODO: Is this needed? Hidden behind an interface in CTP5 implying infrequent usage.
((IObjectContextAdapter)this).ObjectContext.Detach(t);
}
// Owner Classes
public DbSet<MedicalRecordOrder> Orders { get; set; }
public DbSet<Owner> Owners { get; set; }
public DbSet<Pet> Pets { get; set; }
public DbSet<Breed> Breeds { get; set; }
public DbSet<PetProvider> PetProviders { get; set; }
// Security Catalog Items
public DbSet<User> Users { get; set; }
// Bing Maps Catalog items
public DbSet<KnownLocation> KnownLocations { get; set; }
public DbSet<KnownPostalCode> KnownPostalCodes { get; set; }
public DbSet<QueuedEmail> QueuedEmails { get; set; }
public DbSet<InvoicePayment> InvoicePayments { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Schedule> Schedules { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
public DbSet<EmailSubscription> EmailSubscriptions { get; set; }
public DbSet<ResourceAvailabilityUpdate> ResourceAvailabilityUpdates { get; set; }
public DbSet<EmployeeAvailabilityUpdate> EmployeeAvailabilityUpdates { get; set; }
public DbSet<InvoiceConfiguration> InvoiceConfigurations { get; set; }
public DbSet<Vaccine> Vaccines { get; set; }
public DbSet<TourEmail> TourEmails { get; set; }
public DbSet<ReservationRequest> ReservationRequest { get; set; }
//public DbSet<ReservationRequestPets> ReservationRequestPets { get; set; }
public DbSet<Vaccination> Vaccinations { get; set; }
public DbSet<SpecialInstruction> SpecialInstructions { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<VendorStock> VendorStocks { get; set; }
public DbSet<ShoppingCart> ShoppingCarts { get; set; }
public DbSet<SaleDetail> SaleDetails { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SalePayment> SalePayments { get; set; }
public DbSet<PetService> PetServices { get; set; }
public DbSet<PetServicePrice> PetServicePrices { get; set; }
public DbSet<MiscProperty> MiscProperties { get; set; }
public DbSet<ProviderMiscProperty> ProviderMiscProperties { get; set; }
public DbSet<ProviderAuthorizedCreditCard> ProviderAuthorizedCreditCards { get; set; }
public DbSet<AuthorizedCreditCard> AuthorizedCreditCards { get; set; }
public DbSet<ProviderPackage> ProviderPackages { get; set; }
public DbSet<ProviderEmailPreference> ProviderEmailPreferences { get; set; }
public DbSet<EmailType> EmailTypes { get; set; }
public DbSet<RetailSaleReturn> RetailSaleReturns { get; set; }
public DbSet<ServiceRefund> ServiceRefunds { get; set; }
}

问题是DbContext派生类(DataCatalog)的无参数构造函数连接字符串问题

@Pawel的支持下,我解决了我的问题。您只需要为无参数构造函数提供连接字符串,如下所示。

public class DataCatalog : DbContext
{
public static string ConnectionString { get; set; }
public DataCatalog() : base(ConnectionString ?? "PawLoyalty")
{
}  
}

注意1:如果您在单独的层(类库项目)中,则必须在App.Config文件中提供连接字符串。

注意2:完成所有更改后,必须编译您的项目,然后再次运行T4模板

希望这对将来的某个人有所帮助。

我写这篇文章只是基于您的错误代码。您的错误代码显示:

参数"nameOrConnectionString"不能为null、为空或包含只有空白。

所以您的connection string有错误。检查web config中的连接字符串。请确保连接字符串没有空白。

相关内容

  • 没有找到相关文章

最新更新