graham
graham

Reputation: 268

Key not defined exception code first model

Installed Entity Framework using nuget (6.0) setup 2 projects a class library containing the model and a console app, both have EF installed

I have the following model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace IdeaGen.Models
{
    public class User
    {
    [Key]
    public long Id;
    public UserStatus Status;
    public ICollection<UserActivityLog> Logs { get; set; }
    public ICollection<UserMailerLog> MailerLogs { get; set; }
    [MaxLength(255)]
    public string Email { get; set; }
    public DateTime CreatedAt { get; set; }

    public enum UserStatus
    {
        Pending
    }
    public User()
    {
        this.Status = UserStatus.Pending;
        this.CreatedAt = DateTime.Now;

 //            this.Id = Guid.NewGuid();
        this.Logs = new List<UserActivityLog>();
        this.MailerLogs = new List<UserMailerLog>();
    }


    }
}

I attempt to save to the database for the first time using a console app

class Program
{
    static void Main(string[] args)
    {
        var session = new Session();
        var user = new User{Email="[email protected]"};
        Console.WriteLine((user.Id));

        session.Users.Add(user);
        session.SaveChanges();
        Console.WriteLine("Done!");
        Console.Read();

    }
}

and I get an exception on Users.Add(user) Users: EntityType: EntitySet 'Users' is based on type 'User' that has no keys defined.

I originally had the key Id defined as a GUID, also added an explicit [key] attribute to try to get this to work. Any ideas what I am missing? Something in the setup? I have sql server express installed and it is working.

Upvotes: 0

Views: 146

Answers (1)

amiry jd
amiry jd

Reputation: 27585

Entity framework members should be properties; I mean they have to have a public getter and setter method:

Change this:

public long Id;

to this one:

public long Id { get; set; }

Upvotes: 1

Related Questions