I'm using Entity Framework for accessing a SQL Server database.
I have problem with object in table row.
DB (entity code first):
public class User
{
[Key]
public int Id { get; set; }
public Group Group_Id { get; set; }
public string Alias { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Company { get; set; }
}
public class SMAccount
{
[Key]
public int Id { get; set; }
public User User_Id { get; set; } //there he is
public string Type { get; set; }
public string AId { get; set; }
}
Using (view with Razor):
var smAcc = db.SMAccounts.FirstOrDefault(x => x.User_Id.Id.Equals(userID));
if (smAcc != null)
{
<span>FB account: </span>@smAcc.AId <br /> //return accountID
<span>User: </span>@smAcc.User_Id //return null :(
}
but in the table the user is assigned...
ID | type | AId | User_Id_Id
2 | fbu | 227 | 1
How can I take the user object from a table?
Regards
First up, the convention for EF will look for a FK using ClassName_Id, so if you're FK to User is called User_Id then that's covered. You can call your User property "User" rather than "User_Id" which I would think would be confusing because it implies the "Id" of the User, not the user.
public class SMAccount
{
[Key]
public int Id { get; set; }
public User User { get; set; }
public string Type { get; set; }
public string AId { get; set; }
}
Then when retrieving an Account with it's User, use .Include()
to tell EF to eager load the related entitiy.
var smAcc = db.SMAccounts.Include(x => x.User).FirstOrDefault(x => x.User.Id.Equals(userID));
I don't recommend doing this though from the Razor view. Instead make a call to the controller to retrieve a simple C# object that can be populated from the entities. Later on you will likely find yourself having problems with cyclic bi-directional references that the serializer won't iterate through or throw an exception about. Also, by passing entities you are sending far more data to the client than it generally needs which exposes more detail about your data to users than you might render on-screen. By just selecting the data you need to display you minimize the size of the payload across the wire, keep sensitive details hidden from client-side debuggers, and can optimize query performance.