Scott Pantall
Scott Pantall

Reputation: 77

The entity type requires a primary key to be defined error with key attribute

Setting up a proof of concept app. I've added an ApplicationDbContext class and my Transaction class to the Web Application (Model-View-Controller) template in VS2017.

When I try to run Add-Migration AddsTransactions I get this error:

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

Here's my 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; }
    }
}

And my Transaction model class:

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

From what I've read, Entity Framework Core should see that I have a property named Id and make that my primary key and, if for some weird reason it didn't do this, the [Key] attribute should force it to be a primary key.

Unfortunately, reality seems to be disagreeing with me. Any ideas?

Upvotes: 2

Views: 6107

Answers (1)

Scott Pantall
Scott Pantall

Reputation: 77

Today's lesson is "Don't just click on the first thing Intellisense give you, especially when using vague class names"

Turns out I did not want using System.Transactions;, I wanted using WebApplication4.Models in my ApplicationDbContext file.

Upvotes: 2

Related Questions