Reputation: 379
Model1 -
public class model1
{
public long Id { get; set; }
public Guid Unique { get; set; } = Guid.NewGuid();
}
Model2 -
public class model2
{
public long model2Id { get; set; }
public List<model1> Model1Items { get; set; } = new List<model1>();
}
If I wanted to return new
of model2
, how would I do that?
return new
{
model2Id = 3423432,
Model1Items = [
{
Id = 212,
Unique = 23432
}
]
}
I get an error - Invalid expression [
after Model1Items
Upvotes: 1
Views: 711
Reputation: 16081
C# is not as concise as javascript. So, given your code this is how you would do it:
var m2 = new model2()
{
model2Id = 3423432,
Model1Items = new List<model1>()
{
new model1() {Id = 212, Unique = new Guid("23432") },
new model1() {Id = 121, Unique = new Guid("43234") }
// etc...
}
};
For documentation on initializers, see the docs at microsoft here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
Upvotes: 1
Reputation: 7111
Your answer looks very JavaScript-y, but you have it tagged "C#". It's This is how you'd do it:
return new model2
{
model2Id = 3423432,
Model1Items = new List<model1>
{
new model1
{
Id = 212L,
Unique = Guid.NewGuid()
}
}
};
Upvotes: 0
Reputation: 338
Try
return new model2
{
Id = 3423432,
Model1Items = new List<model1>(){
new model1()
{
Id = 212,
Unique = 23432
}
}
}
Upvotes: 0