Entity Framework compilation error. Class cannot be used as scalar property, because it does not have a getter and setter

StackOverflow https://stackoverflow.com/questions/15084718

With Code First approach and implementing a database for an existing system. Therefore I cannot make alot of changes to the existing code. That's why I'm using Fluent API and Entity Framework.

When I'm trying to implement a new class (Vector) which is used by several other classes, I'm getting a compilation error:

The relationship 'Price_Data' was not loaded because the type 'Vector' is not available.
The following information may be useful in resolving the previous error:
The property 'Item' of type 'Vector' in the assembly 'Core, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used as a scalar property because it does not have both a getter and setter.

Since I'm fairly new to .NET (coming from Java) I do not know where to start looking for the error.

Does anyone here know why, and how to fix this?

有帮助吗?

解决方案 3

I found out why this was happening.

Vectorhas an Indexerproperty, aka public var this[]. Thanks to Another StackOverflow post.

As of now, the Fluent API cannot handle this kind of issue, and the simpliest way of adressing this is to use Data Annotation and [NotMapped].

The resulting code would be something like:

class Vector
{
    [NotMapped]
    public var this[]
    {
    }
}

Would like to thank everyone for taken their time trying to help me with this issue.

其他提示

If you read the error message carefully, the problem is very clear:

The property 'Item' of type 'Vector' in the assembly 'Core, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used as a scalar property because it does not have both a getter and setter.

Your class Vector has a property Item which does have a getter or a setter, but not both, and Entity Framework needs read-write properties to work correctly.

Unrelated note: suggestion

If your domain objects don't have their properties marked as virtual (i.e. public virtual string PropertyName), you're not going to take advantage of lazy-loading, meaning that your queries will load the entire result set which ends up in a very inefficient data I/O (more network traffic, greater load times and, at the end of the day, slower applications/services).

If I may be so bold, the error kind of clearly says: The property Item in the type Vector (in assembly Core) does not have both a get and set clause. It would need one if you want to use it with EF.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top