❔ Initializing Entity Relationship Properties

namespace Textopia.Models;

public class Post(string slug)
{
public Guid Id { get; set; } = Guid.NewGuid();

public string Slug { get; set; } = slug;
public string? Name { get; set; }
public string? Content { get; set; }

public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }

public User User { get; set; }
public Blog Blog { get; set; }
}
namespace Textopia.Models;

public class Post(string slug)
{
public Guid Id { get; set; } = Guid.NewGuid();

public string Slug { get; set; } = slug;
public string? Name { get; set; }
public string? Content { get; set; }

public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }

public User User { get; set; }
public Blog Blog { get; set; }
}
How to initialize User and Blog property? Thaaaaaaaanks. 😉
6 Replies
Angius
Angius15mo ago
Make those properties required and don't initialize them
Timo Martinson
Timo MartinsonOP15mo ago
cool what does this lead to ? and where should I put it ?
public required User User { get; set; }
public required Blog Blog { get; set; }
public required User User { get; set; }
public required Blog Blog { get; set; }
is that fine?
Angius
Angius15mo ago
ye It won't allow you to initialize this object without those properties
MODiX
MODiX15mo ago
Angius
REPL Result: Failure
class Foo {
public int Bar { get; set; }
public required int Baz { get; set; }
}

new Foo {
Bar = 69,
// no Baz
}
class Foo {
public int Bar { get; set; }
public required int Baz { get; set; }
}

new Foo {
Bar = 69,
// no Baz
}
Exception: CompilationErrorException
- Required member 'Foo.Baz' must be set in the object initializer or attribute constructor.
- Required member 'Foo.Baz' must be set in the object initializer or attribute constructor.
Compile: 464.230ms | Execution: 0.000ms | React with ❌ to remove this embed.
Timo Martinson
Timo MartinsonOP15mo ago
ok buuuuuuut: ... The required member "Post.User" must be set in the object initializer or attribute constructor. !?!!??! when I try to set it in
app.MapPost("/blogs/{blogSlug}/posts", (string blogSlug) => {
Post post = new(slug: "timo");
});
app.MapPost("/blogs/{blogSlug}/posts", (string blogSlug) => {
Post post = new(slug: "timo");
});
naaa? ok, I finally figured it out! 😉 Thank you nevertheless!
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server