OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.49k stars 6.51k forks source link

[BUG][C#] Project with some inheritance fails to compile. #18838

Open Alysaar opened 4 months ago

Alysaar commented 4 months ago

Bug Report Checklist

Description

I have a C# project where I use swagger to generate the swagger json file, then I use the OpenApi generator CLI to generate the C# api project. The problem I am encountering is that the generated C# api project does not compile.

I have recreated a minimal project that mimics my actual project, I have these two classes :

public abstract class Animal
{
    protected Animal(string sound)
    {
        Sound = sound;
    }

    public virtual string Sound { get; }
    public abstract string TypeName { get; }
}
public class Duck : Animal
{
    public Duck(string sound) : base(sound)
    {
    }

    public override string TypeName { get; } = nameof(Duck);
}

And, once I have generated the csharp api with openapigenerator, I get this :

namespace DuckClient.Model
{
    /// <summary>
    /// Animal
    /// </summary>
    [DataContract(Name = "Animal")]
    [JsonConverter(typeof(JsonSubtypes), "TypeName")]
    [JsonSubtypes.KnownSubType(typeof(Duck), "Duck")]
    public partial class Animal : IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Animal" /> class.
        /// </summary>
        [JsonConstructorAttribute]
        public Animal()
        {
        }

        // rest of code that does not matter for this bug report
    }
}
namespace DuckClient.Model
{
    /// <summary>
    /// Duck
    /// </summary>
    [DataContract(Name = "Duck")]
    [JsonConverter(typeof(JsonSubtypes), "TypeName")]
    public partial class Duck : Animal, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Duck" /> class.
        /// </summary>
        [JsonConstructorAttribute]
        public Duck() : base(sound)
        {
        }

        // rest of code that does not matter for this bug report
    }
}

As you can see, the previous code would not compile, Duck tries to call a base class's constructor that does not exist, with a parameter (sound) that does not exist either.

openapi-generator version

7.3.0

Steps to reproduce

I have created a project that recreates the issue :

  1. Download my test project.
  2. Compile it (this will generate the swagger json file in WebApplication1/Swagger/).
  3. Launch the generate-api.sh script (this will generate the C# api project).
  4. Open that project (in api/ folder).
  5. Compile this project (it fails).

Alternatively you can just get the WebApplication1/Swagger/public-api.json file and generate the C# api project from that.