Required properties and LINQ queries #9391
Replies: 4 comments 4 replies
-
I think And I prefer |
Beta Was this translation helpful? Give feedback.
-
What's the point of making it required if you want to not require it? |
Beta Was this translation helpful? Give feedback.
-
There are two other options: var persons = PersonsQueryable.Select(p=> new { p.FirstName }).ToList(); And: var persons = PersonsQueryable.Select(p=> new Person { FirstName = p.FirstName, ReqProp1 = default, ReqProp2 = default }).ToList(); |
Beta Was this translation helpful? Give feedback.
-
Does Linq allow for constructor parameters in these situations? I'm imagining something like this, but I'm not sure whether it would mess up the public struct PartialTag {
public static PartialTag Partial { get; } = default;
}
public class Person {
public Person() { }
[SetsRequiredProperties]
public Person(PartialTag tag) { }
public required string FirstName { get; set; }
public required string LastName { get; set; }
} and then in consuming code: using static PartialTag;
var persons = PersonsQueryable.Select(p => new Person(Partial) { FirstName = p.FirstName }); (The public static property in |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Imagine something like:
The idea here is to reduce the load on the database and only get the first names of the people (instead of all the properties/columns).
However, if Person has required properties, this doesn't work - it won't compile with CS9035, "Required member ..."
Frankly, I'm not even sure how we could approach improving this. If a keyword is added:
Here,
partial
basically suppresses CS9035 - this can be a pit of failure, like NRT suppress!
operator.Alternatively, if we said that required properties are not enforced in LINQ queries, that "exemption" may be overly broad. Also, what about in-memory (IEnumerable) queries?
I'm curious if anybody has any ideas about this. In the meantime, this kind of precludes me from using required properties on domain entities.
Beta Was this translation helpful? Give feedback.
All reactions