Skip to content

DbContext scaffolding creates reference error CS0120 in nameof() for InverseProperty in certain conditions #26588

Closed

Description

when table names in n:m relations meet certain criteria, the below code is created by dbScaffold (DDL statements at the bottom)

namespace ScaffoldError.database
{
    public partial class MA
    {
        public MA()
        {
            MFMA = new HashSet<MFMA>();
        }

        [Key]
        public int MAId { get; set; }
        [StringLength(50)]
        [Unicode(false)]
        public string? Bezeichnung { get; set; }

        [ForeignKey("MAId")]
        [InverseProperty(nameof(database.MFMA.MA))]
        public virtual ICollection<MFMA> MFMA { get; set; }
    }
}

The problem is line [InverseProperty(nameof(MFMA.MA))] which wants to reference the class called MFMA but actually references the next line's Icollection. this creates compiler error CS0120 "An object reference is required for the non-static field, method, or property 'MFMA.MA'"

The solution is to qualify the MFMA like so [InverseProperty(nameof(database.MFMA.MA))]
I could imagine the issue comes from the naming pattern that one table ends with the other tables names but that's just a guess.

Statement used for scaffolding

dotnet ef dbcontext scaffold "data source=localhost;initial catalog=dbname;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" Microsoft.EntityFrameworkCore.SqlServer `--output-dir "database" --table ma --table mfma --table mfmama --data-annotations --use-database-names --force --no-onconfiguring --no-pluralize 

DDL-Statements:

CREATE TABLE dbo.MA (
  MAId INT IDENTITY
 ,Bezeichnung VARCHAR(50) NULL
 ,CONSTRAINT Pk_ma PRIMARY KEY CLUSTERED (MAId)
) ON [PRIMARY]
GO

CREATE TABLE dbo.MFMA (
  MFMAId INT IDENTITY
 ,Bezeichnung VARCHAR(50) NULL
 ,CONSTRAINT pk_mfma PRIMARY KEY CLUSTERED (MFMAId)
) ON [PRIMARY]
GO

CREATE TABLE dbo.MFMAMA (
  MAId INT IDENTITY
 ,MFMAId INT NOT NULL
 ,CONSTRAINT PK_MFMAMA PRIMARY KEY CLUSTERED (MAId, MFMAId)
) ON [PRIMARY]
GO

ALTER TABLE dbo.MFMAMA
ADD CONSTRAINT FK_MFMAMA_MAId FOREIGN KEY (MAId) REFERENCES dbo.MA (MAId)
GO

ALTER TABLE dbo.MFMAMA
ADD CONSTRAINT FK_MFMAMA_MFMAId FOREIGN KEY (MFMAId) REFERENCES dbo.MFMA (MFMAId)
GO

provider and version information

EF Core version: 6.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: NET 6.0
Operating system:
IDE: (e.g. Visual Studio 20202 current)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions