C
C#2y ago
barcode

❔ EF Core question

public class User : BaseEntity
{
public ulong OAuthId { get; set; }
public Role Role { get; set; }
public ICollection<UserClient> UserClients { get; set; } = null!;
public ICollection<Client> Clients { get; set; } = null!;
}
public class User : BaseEntity
{
public ulong OAuthId { get; set; }
public Role Role { get; set; }
public ICollection<UserClient> UserClients { get; set; } = null!;
public ICollection<Client> Clients { get; set; } = null!;
}
Currently I define my models like this, should these collections be defined as null! or should I do new List<Client>() in the class?
var clients = _clients.GetClients()
.Where(x => createUserDto.ClientIds!.Contains(x.Id));
// TODO: add clients
user.Clients = new List<Client>();
clients.ToList().ForEach(x=> user.Clients.Add(x));

await _users.CreateUser(user);
var clients = _clients.GetClients()
.Where(x => createUserDto.ClientIds!.Contains(x.Id));
// TODO: add clients
user.Clients = new List<Client>();
clients.ToList().ForEach(x=> user.Clients.Add(x));

await _users.CreateUser(user);
currently I add clients when I create an user like this
5 Replies
Pobiega
Pobiega2y ago
null! will be fine if you always get these from EF, but it will be iffy if you ever do var x = new User()
barcode
barcodeOP2y ago
how do I create a new user without doing new User? rn i just do new User() then user.Clients = new List<Client>(); can't find convention in msdn
Pobiega
Pobiega2y ago
You could make the constructor private/protected, and make a static creation method ie
public User Create(...)
{
return new User(...)
{
Clients = new List<Client>();
UserClients = new List<UserClient>();
};
}
public User Create(...)
{
return new User(...)
{
Clients = new List<Client>();
UserClients = new List<UserClient>();
};
}
barcode
barcodeOP2y ago
ty
Accord
Accord2y ago
Looks like nothing has happened here. 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