【发布时间】:2018-04-17 22:41:00
【问题描述】:
设置概念验证应用程序。我在 VS2017 的 Web Application (Model-View-Controller) 模板中添加了一个 ApplicationDbContext 类和我的 Transaction 类。
当我尝试运行 Add-Migration AddsTransactions 时,我收到此错误:
实体类型“交易”需要定义一个主键。
这是我的ApplicationDbContext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
namespace WebApplication4.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Transaction> Transactions { get; set; }
}
}
还有我的Transaction 模型类:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication4.Models
{
public class Transaction
{
[Key]
public int Id { get; set; }
public DateTimeOffset TransactionDate { get; set; }
public decimal TransactionAmount { get; set; }
public bool OnHold
{
get { return this.FundingStatus == FundingStatus.Held; }
set { this.FundingStatus = FundingStatus.Held; }
}
public FundingStatus FundingStatus { get; set; }
}
public enum FundingStatus
{
New,
Submitted,
Funded,
Held
}
}
根据我的阅读,Entity Framework Core应该看到我有一个名为 Id 的属性并将其作为我的主键,如果出于某种奇怪的原因它没有这样做,[Key] 属性应该强制它成为主键。
不幸的是,现实似乎不同意我的看法。有什么想法吗?
【问题讨论】:
-
您使用的是什么版本的 EF?我相信,在 EF 的早期版本中,枚举需要属性。我认为 EF5 及更高版本应该没问题,因为你有它。可能是 EF 引发了异常。此外,我个人从未见过 get / set 首先具有 EF 代码的条件,但这并不是说它不能。我的经验从未涉及它。
-
@MichaelPuckettII 我正在使用 Entity Framework Core 2.0.2
标签: c# entity-framework visual-studio-2017 entity-framework-core primary-key