Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Owned type cannot be specified in owner entity's parameterised ctor #3723

Closed
lonix1 opened this issue Feb 7, 2022 · 2 comments
Closed

Owned type cannot be specified in owner entity's parameterised ctor #3723

lonix1 opened this issue Feb 7, 2022 · 2 comments

Comments

@lonix1
Copy link

lonix1 commented Feb 7, 2022

The owned types page explains how to use value objects. The constructors page explains how to use parameterised ctors. But there is no mentioned of how to do that together.

public sealed class Foo
{
    public string Something { get; private set; }
    public Bar Bar { get; private set; }     // owned type

    public Foo(string something, Bar bar)                  // won't work
    {
        Something = something;
        Bar = bar;
    }
}

EF will throw an exception due to that ctor. That is because Bar is an owned type, and it is treated as a navigation property.

To make this work we must remove Bar from the ctor. EF will then run the ctor, and then populate the property separately.

The page should also explicitly mention

Owned types are treated as navigation properties


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

@ajcvickers
Copy link
Contributor

Covered by #1627.

See also dotnet/efcore#26398, which changed the message in EF7 to something like this:

No suitable constructor was found for entity type 'BlogNone'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'did' in 'BlogNone(string title, int did)'; cannot bind 'notTitle' in 'BlogNone(string notTitle, Guid? shadow, int id)'; cannot bind 'dummy' in 'BlogNone(string title, Guid? shadow, bool dummy, int id)'; cannot bind 'dummy', 'description' in 'BlogNone(string title, Guid? shadow, bool dummy, int id, string description)'. Note that only mapped properties can be bound to constructor parameters. Navigations to related entities, including references to owned types, cannot be bound.

@lonix1
Copy link
Author

lonix1 commented Feb 7, 2022

Looks good, I'm sure it'll help others who stumble over that.

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

No branches or pull requests

2 participants