Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定義主鍵

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

我無法克服這個錯誤。我只是想把一個商品列表放到一個下拉列表中。使用:Asp.Net Core 1.0 EntityFramework Core。 MVC存儲庫模式。

我已經嘗試了所有我用Google搜索過的東西。我的Guid / Oid PK有[Key]屬性。 (它是一個GUID問題??)我在我的DBContext類中添加了HasKey()到我正在使用的Entity / ViewModel。我把它映射到原始模型/商品表(這是正確的??)

我在實體框架中使用Microsoft逆向工程師對現有數據庫執行了DB First: https//docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html#reverse-engineer-your-model

此時,我甚至不確定我是否正在連接到我的數據庫。我還沒有看到任何數據。

我完全失去了。感謝幫助。

這是我的啟動課程:

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> ();


    }
}

這是我的DBContext類:

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

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

我的界面:

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

                        }

熱門答案

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

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

或者忽略類型本身:

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因