Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup' requires a primary key to be defined

asp.net-core-mvc c# entity-framework-core selectlistitem

Question

I cannot get past this error. I'm simply trying to get a list of commodities into a drop down. Using: Asp.Net Core 1.0 EntityFramework Core. MVC Repository Pattern.

I've tried everything I've Googled. I have [Key] attribute over my Guid/Oid PK. (Is it an GUID issue??) I have added HasKey() in my DBContext Class to the Entity/ViewModel I am using. I have it mapped to the original model/Commodity Table (is this correct??)

I did DB First to existing DB using Microsoft reverse engineer in Entity Framework:https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html#reverse-engineer-your-model

At this point, I'm not even sure if I am connecting to my DB. I haven't seen any data pull through.

I'm at a total loss. Help is appreciated.

Here is my start up class:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<ltgwarehouseContext>(options => options.UseSqlServer(Configuration["DefaultConnection:ConnectionString"]));
        services.AddMvc();
        services.AddSingleton<ICommodityRepository, CommodityRepository> ();


    }
}

This is my DBContext Class:

        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");
             });
    }
  }

My ViewModel:

    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;}
}

My Interface:

public interface ICommodityRepository
{

    IEnumerable<CommodityViewModel> GetCommodities();

}

My Repository (This is where the error gets thrown when debugging)

public class CommodityRepository : ICommodityRepository
{    
    private readonly ltgwarehouseContext  _context;


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

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

}

Stack Trace:

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: 

My Controller Action:

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

And finally, My 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>
                            }

                        }
1
0
10/20/2016 3:34:23 PM

Popular Answer

You need to remove CommodityViewModel.CommoditiesList or at least ignore it:

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

Or ignore the types themselves:

 modelBuilder.Ignore<SelectListItem>();
 modelBuilder.Ignore<SelectListGroup>();
1
11/2/2016 7:29:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow