Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定义主键

时间:2016-10-20 15:34:23

标签: c# asp.net-core-mvc entity-framework-core selectlistitem

我无法理解这个错误。我只是想把一个商品列表放到一个下拉列表中。使用: Asp.Net Core 1.0 EntityFramework核心。 MVC 存储库模式。

我已经尝试了所有我用Google搜索过的东西。 我的Guid / Oid PK有[Key]属性。 (这是一个GUID问题吗?) 我已将DBContext类中的HasKey()添加到我正在使用的Entity / ViewModel中。 我把它映射到原始模型/商品表(这是正确的??)

我使用实体框架中的Microsoft逆向工程师对现有数据库执行了DB First:COMPOSE_FILE environment variable pointing to your file

此时,我甚至不确定我是否正在连接到我的数据库。我没有看到任何数据通过。

我完全失去了。感谢帮助。

这是我的启动课程:

        public partial class ltgwarehouseContext : DbContext
    {
//        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//        {
////#warning// To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
//            optionsBuilder.UseSqlServer(@"Server=.;Database=ltgwarehouse;Trusted_Connection=True;");
//        }
        public ltgwarehouseContext(DbContextOptions<ltgwarehouseContext> options)
            : base(options)
        { }


        //public ltgwarehouseContext()
        //{
        //}
       public DbSet<CommodityViewModel> CommoditiesList { get; set; }

        public DbSet<Commodity> Commodities { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CommodityViewModel>(entity =>
             {
                 modelBuilder.Entity<CommodityViewModel>().ToTable("Commodity");
                 modelBuilder.Entity<CommodityViewModel>().HasKey(c => c.Oid);
                 //.HasName("PK_Commodity");
             });
    }
  }

这是我的DBContext类:

    public partial class CommodityViewModel
    {
        public CommodityViewModel()
        {

        }

        public IEnumerable<SelectListItem> CommoditiesList { get; set; }
        [Key]
        public Guid Oid { get; set; }

        public string Code { get; set; }

        public string Description { get; set;}
}

我的ViewModel:

public interface ICommodityRepository
{

    IEnumerable<CommodityViewModel> GetCommodities();

}

我的界面:

public class CommodityRepository : ICommodityRepository
{    
    private readonly ltgwarehouseContext  _context;


    public CommodityRepository(ltgwarehouseContext context)
    {
        _context = context;
    }

    public IEnumerable<CommodityViewModel> GetCommodities()
    {
        return _context.CommoditiesList.ToList();
    }

}

我的存储库(这是调试时抛出错误的地方)

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The entity type 'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup' requires a primary key to be defined.
  Source=Microsoft.EntityFrameworkCore
  StackTrace:
       at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)
       at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model)
       at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model)
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
       at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
       at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.<.ctor>b__2_0()
       at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at Lansing.BasisMap.Domain.CommodityRepository.GetCommodities() in C:\LTG Projects\Basis Map\Lansing.Geo\Lansing.BasisMap.Domain\Models\Repositories\CommodityRepository.cs:line 52
       at Lansing.BasisMap.Controllers.HomeController.Index() in C:\LTG Projects\Basis Map\Lansing.Geo\Lansing.BasisMap\Controllers\HomeController.cs:line 30
       at lambda_method(Closure , Object , Object[] )
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionFilterAsync>d__28.MoveNext()
  InnerException: 

堆栈追踪:

public IActionResult Index()
{
    ViewBag.Commodities = _commoditiyRepository.GetCommodities().Select( c => new SelectListItem() { Text = c.Code, Value = c.Oid.ToString() } ).Cast<CommodityViewModel>().ToList();
     return View();
}

我的控制器操作:

@model MyCompany.BasisMap.Domain.Models.CommodityViewModel
                        @if (ViewBag.Commodities == null)
                        {
                            throw new Exception("No Data!");

                        }
                        else
                        {
                            foreach (var commoditiy in ViewBag.Commodities)
                            {
                                <li>
                                    @commoditiy.code
                                </li>
                            }

                        }

最后,我的观点:

Device Admin

1 个答案:

答案 0 :(得分:0)

您需要删除CommodityViewModel.CommoditiesList或至少忽略它:

 modelBuilder.Entity<CommodityViewModel>().Ignore(c => c.CommoditiesList);

或者忽略类型本身:

 modelBuilder.Ignore<SelectListItem>();
 modelBuilder.Ignore<SelectListGroup>();