Reputation:
So I have been following this tutorial on ASP.NET. I have created a Model and intend on generating a Controller with views, using Entity Framework. However I have been stuck on this error for nearly hours researching causes and its only 2 lines of code and I can't for the life of me understand how I am getting this error.
Link to Tutorial https://mva.microsoft.com/en-US/training-courses/introduction-to-asp-net-mvc-8322?l=Omf358Zy_1604984382
Upvotes: 0
Views: 1248
Reputation: 76547
Using the [Key]
Attribute
Consider setting a [Key]
attribute on the primary key for this class :
[Key]
public int TaskID { get; set; }
This data attribute will let Entity Framework know how to properly recognize this as an identifier for this entity when performing queries, updates, etc.
Using Built-In Conventions
Entity Framework can usually automatically identify it your field as referenced in this Code First Conventions article :
Previously Code First would infer that a property is a primary key if the property is called
Id
or<class name>Id
.The only change to this convention is that once primary key properties are detected if their type is ‘int’, ‘long’ or ‘short’, they are registered as identity columns in the database by default. Primary key detection is not case sensitive.
Upvotes: 1
Reputation: 5314
[Key]
should work, remember to rebuild your project. If you've already got migrations for creating the schema then you will have to either change them, or add a new one.
I would recommend changing your class name to Task
instead of Tasks
. Your class looks like a singular item, not a list of items. This should help in a couple of ways:
TaskID
(it looks for field that is either labelled only ID, or <classname>ID
if I remember correctly). You won't have to force it with the [Key]
annotation.
Tasks
, which should be more correct: a set of Task
s, instead of being a set called Tasks
which holds several individual Tasks
items. I think C# can tell the difference, but can you, without inspecting each reference? Upvotes: 0
Reputation: 2020
Here we go:
You should to add the [KEY] attribute for your TaskID like this code:
public class Tasks
{
[Key]
public int TaskID {get;set;}
public string taskStatus {get;set;}
}
Hope it helps;)
Upvotes: 0
Reputation: 1493
Entity framework expects a primary key, you can add it by
[Key]
public int TaskID { get; set; }
Or try renaming it
public int TasksID { get; set; }
Upvotes: 1
Reputation: 1324
In EntityFramework, when you try to set a primary key, you can work with dataannotations or conventions. If you use conventions it needs to be <className>Id
or just Id
. Else you need to specify [Key]
above the property.
Upvotes: 0