0

I'm learning EF code first and my experience with c# is limited.

I created an entity but I didn't put { get; set; }. EF failed to detect the key. After adding { get; set; }, it detected.

I wonder what's the difference having / not having { get; set; } ?

public class Category
{
    public int CategoryId { get; set; }

    public string CategoryName { get; set; } = "";
}

and

public class Category
{
    public int CategoryId
    public string CategoryName
}

Thanks.

tmsbrndz
  • 1,297
  • 2
  • 9
  • 23
EBDS
  • 1,244
  • 5
  • 16
  • 4
    Essential reading: [What is the difference between a field and a property?](https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property) – madreflection Nov 15 '22 at 16:55
  • 1
    Are you using EF6 or EF Core? Not that it matters, as in both cases EF does not support binding query-result columns to fields, only properties. – Dai Nov 15 '22 at 16:56
  • @Dai I think I'm using EF Core, not EF6. Actually, I didn't know there is a EF6 and EF Core. I'll read up on that. Thanks. – EBDS Nov 15 '22 at 16:59
  • 2
    @EBDS EF6 is older and now EOL'd, EF Core is its replacement, but the two didn't reach feature-parity until very recently - that's why a lot of people still use EF6 today. (Also, EF Core _only_ runs on .NET Core/.NET 5+, while EF6 is for .NET Framework 4.x - but also supports .NET Core 3.1+/.NET5+ to support transitioning to the future. – Dai Nov 15 '22 at 17:00
  • @madreflection oh. I thought there is one (ie properties) and that I can have get/set or not. Learn something new. I'm more used to Python and I think there is no difference. May be I'm wrong there also. Thanks. – EBDS Nov 15 '22 at 17:01
  • @Dai then I'm fine, I guess since I just started. ;-) – EBDS Nov 15 '22 at 17:02
  • 2
    Python's _Object Attributes_ are roughly equivalent to C#/.NET _Object Properties_ - with some minor differences. – Dai Nov 15 '22 at 17:03
  • 1
    If you just started, you should be using EF Core. First, make sure you are. Second, retag with [tag:entity-framework-core] to match. – madreflection Nov 15 '22 at 17:03
  • 2
    @EBDS Protip: in a C# `class`, the syntax `public String MyProperty { get; set; }` _is shorthand_ for a property with its own _backing field_ (e.g. `private String myPropertyField;`). This can throw beginners off who might reasonably think that somehow properties and fields are entirely unrelated. – Dai Nov 15 '22 at 17:05

0 Answers0