我正在开发一个控制台应用程序,该应用程序使用称为Entity Framework Core的C#/。NET框架,该框架可与SQLite数据库语言一起使用。到目前为止,此应用程序应该做的是输出假冒公司拥有的所有产品类别以及每个类别中有多少产品。
输出如下所示:
Categories and how many products they have:
Beverages has 12 products.
Condiments has 12 products.
Confections has 13 products.
Dairy Products has 10 products.
Grains/Cereals has 7 products.
Meat/Poultry has 6 products.
Produce has 5 products.
Seafood has 12 products.
但是无论何时运行该应用程序,这都是我得到的输出:
Categories and how many products they have:
Unhandled exception. microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such column: c.Products.Discontinuted'.
at microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc,sqlite3 db)
at microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at microsoft.Data.Sqlite.SqliteCommand.ExecuteDbdataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection,DbCommandMethod executeMethod,IReadOnlyDictionary`2 parameterValues)
at microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection,IReadOnlyDictionary`2 parameterValues)
at microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(Boolean buffer)
at microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c,TState s)
at microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](TState state,Func`3 operation,Func`3 verifySucceeded)
at microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy,Func`2 operation,Func`2 verifySucceeded,TState state)
at microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TState state,Func`2 operation)
at microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.IncludeCollection(Int32 includeId,INavigation navigation,INavigation inverseNavigation,IEntityType targetEntityType,IClrCollectionaccessor clrCollectionaccessor,IClrPropertySetter inverseclrPropertySetter,Boolean tracking,Object entity,Func`1 relatedEntitiesFactory)
at lambda_method(Closure,QueryContext,Category,Object[] )
at microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler._Include[TEntity](QueryContext queryContext,TEntity entity,Object[] included,action`3 fixup)
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable`1 results,QueryContext queryContext,IList`1 entityTrackingInfos,IList`1 entityaccessors)+MoveNext()
at microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at WorkingWithEFCore.Program.QueryingCategories() in /Users/steelwind/HardWay/c#and.NET/Chapter11/WorkingWithEFCore/Program.cs:line 24
at WorkingWithEFCore.Program.Main(String[] args) in /Users/steelwind/HardWay/c#and.NET/Chapter11/WorkingWithEFCore/Program.cs:line 12
这是我主文件中的代码:
using static System.Console;
using Packt.CS7;
using microsoft.EntityFrameworkCore;
using System.Linq;
namespace WorkingWithEFCore
{
class Program
{
static void Main(string[] args)
{
QueryingCategories();
}
static void QueryingCategories()
{
using (var db = new Northwind())
{
WriteLine("Categories and how many products they have:");
// a query to get all categories and their related products
IQueryable<Category> cats = db.Categories.Include(c => c.Products);
foreach (Category c in cats)
{
WriteLine($"{c.CategoryName} has {c.Products.Count} products.");
}
}
}
}
}
这是处理类别的文件的代码:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace Packt.CS7
{
public class Category
{
// these properties map to columns in the database
public int CategoryID { get; set; }
public string CategoryName { get; set; }
[Column(TypeName = "ntext")]
public string Description { get; set; }
// defines a navigation property for related rows
public virtual ICollection<Product> Products { get; set; }
public Category()
{
// to enable developers to add products to a Category we must
// initiate the navigation property to an empty list
this.Products = new List<Product>();
}
}
}
以下是处理产品的代码:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Packt.CS7
{
public class Product
{
public int ProductID { get; set; }
[Required]
[StringLength(40)]
public string ProductName { get; set; }
[Column("UnitPrice",TypeName = "money")]
public decimal? Cost { get; set; }
[Column("UnitsInStock")]
public short? Stock { get; set; }
public bool Discontinuted { get; set; }
// these two define the foriegn key relationship
// to the Category table
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
}
这是连接到数据库的代码:
using microsoft.EntityFrameworkCore;
namespace Packt.CS7
{
// this manages the connect to the database
public class Northwind : DbContext
{
// these properties map to tables in the database
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
protected override void Onconfiguring(DbContextOptionsBuilder optionsBuilder)
{
// to use SQLite,uncomment the following
string path = System.IO.Path.Combine(
System.Environment.CurrentDirectory,"Northwind.db");
optionsBuilder.UseSqlite($"Filename={path}");
}
protected override void OnmodelCreating(ModelBuilder modelBuilder)
{
// example of using Fluent API instead of attributes
// to limit the length of a category name to under 40
modelBuilder.Entity<Category>()
.Property(category => category.CategoryName)
.isrequired()
.HasMaxLength(40);
}
}
}