I’m working with WebMatrix and EntityFramework.
In my database I have a user table, in our business logic a user can create or update the content of another table, so my user class in my model is like this:
[Table("Users")]
public class User
{
[Key]
public int UserId { get; set; }
[MaxLength(50), MinLength(5), Required]
public string UserName { get; set; }
[MaxLength(16), MinLength(8), Required]
public string Password { get; set; }
[MaxLength(50), Required]
public string Name{ get; set; }
[MaxLength(50), Required]
public string LasName1{ get; set; }
[MaxLength(50), Required]
public string LasName2{ get; set; }
public string token { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime UpdatedDateTime { get; set; }
[InverseProperty("CreatedBy")]
public virtual ICollection<Device> CreatedDevices {get; set;}
[InverseProperty("UpdatedBy")]
public virtual ICollection<Device> UpdatedDevices {get; set;}
[InverseProperty("CreatedBy")]
public virtual ICollection<Cluster> CreatedClusters {get; set;}
[InverseProperty("UpdatedBy")]
public virtual ICollection<Cluster> UpdatedClusters {get; set;}
[InverseProperty("CreatedBy")]
public virtual ICollection<Region> CreatedRegions {get; set;}
[InverseProperty("UpdatedBy")]
public virtual ICollection<Region> UpdatedRegions {get; set;}
}
For exampl,e my Region class looks like this:
[Table("Regions")]
public class Region
{
[Key]
public int RegionId { get; set; }
[MaxLength(50), MinLength(5), Required]
public string Name{ get; set; }
public virtual ICollection<Cluster> Clusters { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime UpdatedDateTime { get; set; }
public Usuario CreatedBy { get; set; }
public Usuario UpdatedBy { get; set; }
}
This creates the necessary relationships between the entities in the database. Now comes my main doubt, in my Cluster table there’s a CreatedBy_UserId, so when I’m doing the insert or update of an entry in the table, do I have to pass a User object? I’m saying something like this
Cluster cluster = new Cluster()
{
RegionId = regionId,
CreatedDateTime = createdDateTime,
UpdatedDateTime = updatedDateTime,
CreatedBy = currentUser,
UpdatedBy = currentUser
};
Or how do I pass an int representing the foreign key to the table?
If you don’t have a foreign key property in your model, then yes, you need to set the navigation properties to establish a relationship. You only must make sure that
currentUseris attached to the context – by loading it from the DB or attaching manually. Otherwise EF would also create new users. An example is this:SaveChangeswill create anINSERTstatement with the correct foreign key values (equal tocurrentUser.UserId) set.