c# - 实体类型需要定义主键,且 key 属性错误

标签 c# entity-framework visual-studio-2017 entity-framework-core primary-key

设置概念验证应用。我已将 ApplicationDbContext 类和我的 Transaction 类添加到 VS2017 中的 Web 应用程序(模型- View - Controller ) 模板。

当我尝试运行 Add-Migration AddsTransactions 时,出现此错误:

The entity type 'Transaction' requires a primary key to be defined.

这是我的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] 属性应该强制它成为主键。

不幸的是,现实似乎与我不符。有什么想法吗?

最佳答案

今天的类(class)是“不要只点击 Intellisense 给你的第一件事,尤其是在使用模糊的类名时”

结果我不想使用 System.Transactions;,我想在我的 ApplicationDbContext 文件中使用 WebApplication4.Models

关于c# - 实体类型需要定义主键,且 key 属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888526/

相关文章:

c# - 如何在 Lambda LINQ 表达式中创建 LEFT JOIN

.net - Reload() 不更新 EF 实体

entity-framework - 数据库设计 : more tables vs less tables

.net - 如何为 Oracle 数据库创建 Visual Studio 数据库项目?

powershell - NuGet - 从命令行添加新的包源

c# - 在设置 Windows 服务时遇到问题

c# - Bot 在 MS TEAMS channel 中尝试发送自适应卡时抛出 "Operation returned an invalid status code ' RequestEntityTooLarge'”异常

c# - 对如何组织我的类(class)有疑问

c# - 如何将 Visual Studio Text Visualizer 用于自定义类型?

azure - 尝试发布 Azure API。 VS2017似乎没有最新的Azure SDK