Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup& # 39;要求定
本文关键字:AspNetCore Mvc Rendering SelectListGroup Microsoft | 更新日期: 2023-09-27 18:13:57
我无法越过这个错误。我只是想把商品列表放到一个下拉列表中。使用:Asp。Net Core 1.0EntityFramework核心。MVC库模式。
我已经试过所有我在谷歌上搜索过的东西了。我在我的Guid/Oid PK上有[Key]属性(这是Guid问题吗??)我已经在我的DBContext类中添加了HasKey()到我正在使用的实体/视图模型。我已将其映射到原始型号/商品表(这是正确的吗??)我做了DB首先到现有的数据库使用微软在实体框架逆向工程: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");
});
}
}
我的视图模型:
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();
}
My Repository(这是调试时抛出错误的地方)
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:
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();
}
最后,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>
}
}
您需要删除CommodityViewModel.CommoditiesList
或至少忽略它:
modelBuilder.Entity<CommodityViewModel>().Ignore(c => c.CommoditiesList);
或者忽略类型本身:
modelBuilder.Ignore<SelectListItem>();
modelBuilder.Ignore<SelectListGroup>();