想象一下特德。特德使用公告板。他可以发布广告并订阅广告(例如,广告是一些活动......教学课程)。所以你猜对了我们有两个对象:广告和用户(特德)。一个用户 发布 不同的广告,另一方面,一个用户 订阅 用于不同的广告。因此,我们有两种类型的关系:一对多(Ted to his adverts)和多对多(广告给订阅者 - 广告订阅者)。 所以模型看起来像:
[Table("Users")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name="Login")]
[Required(ErrorMessage = "Enter the login.")]
public string Name { get; set; }
[Required(ErrorMessage = "Select the city.")]
public int CityId { get; set; }
public City City { get; set; }
public int? SpecialityId { get; set; }
public Speciality Speciality { get; set; }
public virtual ICollection<Advert> Adverts { get; set; }
public virtual ICollection<Advert> SubscribedOnAdverts { get; set; }
public User()
{
Adverts = new List<Advert>();
SubscribedOnAdverts = new List<Advert>();
}
}
广告:
public class Advert
{
public int Id { get; set; }
[Required(ErrorMessage = "Enter your ad title")]
public string Title { get; set; }
[Required(ErrorMessage = "Enter your ad text")]
[Display(Name="Advert text")]
public string Description { get; set; }
public int? Price { get; set; }
[DisplayName("Owner")]
[Required(ErrorMessage = "Select ad owner")]
public int UserId { get; set; }
public User User { get; set; }
[DisplayName("Speciality")]
[Required(ErrorMessage = "Enter the speciality")]
public int SpecialityId { get; set; }
public Speciality Speciality { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime publishTime { get; set; }
public virtual ICollection<User> SubscribedUsers { get; set; }
public Advert() {
publishTime = DateTime.Now;
SubscribedUsers = new List<User>();
}
}
让我们看一下用户模型:你可以看到相同类型的道具:广告,订阅了OnAdverts。如果我们从广告模型中删除用户模型和SubscribedUsers的SubscribedOnAdverts属性,则以下代码将更正:
IEnumerable<Advert> userAdverts = db.Users.Where(usr => usr.Id == id).FirstOrDefault().Adverts;
它将返回此用户发布的广告。 但是通过上述特性(用户模型中的SubscribedOnAdverts,广告模型中的SubscribedUsers),它将返回空集合。
我可以猜到它为什么会发生。但我不知道如何解决这个问题并保存关系。