【发布时间】:2019-01-04 09:42:13
【问题描述】:
希望你能帮帮我我要绑定 DropDownList 并从现有数据库中获取数据。 Visual Studio 没有显示错误,但是当我运行应用程序时,它会告诉我迁移我的数据库,即使我已经迁移了它。 这是我的代码。
创建.cs
<div class="form-group">
<label asp-for="DomWasAccNo" class="control-label"></label>
<select asp-for="DomWasAccNo"
class="form-control"
asp-items="@(new SelectList(@ViewBag.ListOfConsumer, "AccountNo","AccountNo"))"></select>
<span asp-validation-for="DomWasAccNo" class="text-danger"></span>
</div>
LibCustomers.cs 此部分是使用此 CLI 命令“dotnet ef dbcontext scaffold "Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;" Microsoft.EntityFrameworkCore.SqlServer -d -o Model -c "CustomerDbContext"
自动生成的using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WWFS.Models
{
[Table("LIB_CONSUMERS")]
public partial class LibConsumers
{
[Column("account_no")]
[StringLength(15)]
public string AccountNo { get; set; }
[Column("consumer_name")]
[StringLength(255)]
public string ConsumerName { get; set; }
[Column("address")]
[StringLength(255)]
public string Address { get; set; }
}
}
Controller.cs
List<LibConsumers> libConsumers = new List<LibConsumers>();
libConsumers = (from cons in _context.LibConsumers
select cons).ToList();
libConsumers.Insert(0, new LibConsumers { AccountNo = "Select" });
ViewBag.ListOfConsumer = libConsumers;
DomesticWaste.cs
using Microsoft.EntityFrameworkCore;
namespace WWFS.Models
{
public class DomesticWasteDbContext : DbContext
{
public DomesticWasteDbContext(DbContextOptions<DomesticWasteDbContext> options)
: base(options)
{
}
public DbSet<WWFS.Models.DomesticWaste> DomesticWastes { get; set; }
public DbSet<WWFS.Models.Location> Locations { get; set;}
public DbSet<WWFS.Models.Contractor> Contractors { get; set; }
public DbSet<WWFS.Models.LibConsumers> LibConsumers { get; set; }
}
}
CustomerDbContext.cs 此部分是使用此 CLI 命令“dotnet ef dbcontext scaffold "Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;" Microsoft.EntityFrameworkCore.SqlServer -d -o Model -c "CustomerDbContext"
自动生成的using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WWFS.Models
{
public partial class CustomerDbContext : DbContext
{
public virtual DbSet<LibConsumers> LibConsumers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LibConsumers>(entity =>
{
entity.Property(e => e.AccountNo).ValueGeneratedNever();
entity.Property(e => e.ConsumerName).ValueGeneratedNever();
entity.Property(e => e.Address).ValueGeneratedNever();
});
}
}
}
【问题讨论】:
-
那么发生了什么?你有错误吗?
-
错误是
InvalidOperationException: The entity type 'LibConsumers' requires a primary key to be defined.
标签: entity-framework asp.net-core-mvc asp.net-core-2.0