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

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

Question

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?

1
2
4/18/2018 7:57:18 AM

Popular Answer

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.

2
4/17/2018 11:27:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow