我目前正在使用Entity Framework Core和Net Core 2.1 Web应用程序学习如何指示用户是否订阅了指定的新闻。
我花了一天的时间试图了解如何使用Linq查询方法来处理这种情况。
我有3个表(用户、新闻和订阅)。
1.1. 在 Subscriptions
表中必须存储新闻ID,即用户订阅的ID(用户ID旁边)。
假设当用户订阅时,他们可以收到新闻的通知,否则不能。
我的问题来了,当我试图检查用户是否订阅了那个指定的新闻。我还需要返回那个人订阅的新闻(我基本上没有正确查询)。我试过用 Include()
方法,但我觉得我好像少了点什么。
这是我的代码。
DataContext:
public class DataContext : IdentityDbContext<User, Role, string>
{
public DbSet<News> News { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Subscription>(s =>
{
s.HasKey(x => new
{
x.UserId,
x.NewsId
});
});
}
}
User entity:
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Subscription> Subscriptions { get; set; }
}
News
实体:
public class News
{
public string Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public ICollection<Subscription> Subscriptions { get; set; }
}
实体:Subscription实体。
public class Subscription
{
public string UserId { get; set; }
public string NewsId { get; set; }
public News News { get; set; }
public User User { get; set; }
}
NewsModel
在View中使用的模型(UserModel包含与User相同的基本属性)。
public class NewsModel
{
public string Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public UserModel UserCreate { get; set; }
}
User
和 News
多对多的关系 Subscription
是两个类之间的连接。
查询多对多关联的一般模式是
from news in context.News
from un in news.Subscriptions
let user = un.User
select ...
现在你可以 select
任何财产 news
和 user
来将两个类的数据呈现在一个平面列表中。
select new NewsModel
{
Id = news.Id,
Title = news.Title,
Content = news.Content,
UserCreate = new UserModel
{
FirstName = user.FirstName,
LastName = user.LastName
}
}
附注:我会使用一个像 NewsItem
,更容易区分单数和复数名称。