我正在使用 WebMatrix 和 EntityFramework。
在我的数据库中,我有一个用户表,在我们的业务逻辑中,用户可以创建或更新另一个表的内容,所以我的模型中的用户类是这样的:
[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;}
}
例如,我的 Region 类如下所示:
[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; }
}
这会在数据库中的实体之间创建必要的关系。现在是我的主要疑问,在我的集群表中有一个 CreatedBy_UserId,所以当我在表中插入或更新条目时,我是否必须传递一个用户对象?我在说这样的话
Cluster cluster = new Cluster()
{
RegionId = regionId,
CreatedDateTime = createdDateTime,
UpdatedDateTime = updatedDateTime,
CreatedBy = currentUser,
UpdatedBy = currentUser
};
或者如何将表示外键的 int 传递给表?