Skip to content

CSharpHelper: support more types of collection literals #19274

@AdrianoAE-Surface

Description

@AdrianoAE-Surface

I've been hacking around trying to extend the modelbuilder and I came across this CSharpHelper and need some clarifications.
Class:

public class ConfigTest
{
    public Type Type { get; set; }
    public string ForeignKeyName { get; set; }
}

And i'm adding a annotation to the EntityTypeBuilder

IEnumerable<ConfigTest> config = new List<ConfigTest>() { ... }
builder.Metadata.AddAnnotation("ConfigTestKey", config);

But then when creating the migration the following error is thrown

The current CSharpHelper cannot scaffold literals of type 'System.Collections.Generic.List`1[ConfigTest]'. Configure your services to use one that can.

So after digging around I got to the CSharpHelper and the UnknownLiteral. After messing around trying to understand what I had to do I ended up doing this for no reason and it worked

public override string UnknownLiteral(object value)
{
    if (value is IEnumerable<ConfigTest> configuration)
    {
        var test = configuration.Select(x => "").ToArray();
        return Literal(test);
    }

    return base.UnknownLiteral(value);
}

After that and injecting my custom CSharpHelper everything works and I can use my List as value of the annotation. But how does it work? Why passing a empty array of strings with the size of my List works and the actual value can be casted back to the List when building the model. What is going on under the hood?

I couldn't find mutch information about the CSharpHelper or even how to implement the UnkownLiteral, I just got it working by accident and I don't understand why it works.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions