关于MVC3种IOC自写方法GetItems("Model名字")得到的Model为空的解决方法
在项目中的PostRepository中往往会写到方法GetItems("Model") Model为关联的实例对象名称 并且这个Model还是Post的一个属性
例如在对象Post中
public class Post
{
public int Id{get;set;}
public int AdminId{get;set;}
public Admin admin{get;set;}
}
PostRepository.GetItems("Admin")
如果在查询的结果中出现post有值,adminId有值 但是Admin为null
这是你可以查看一下方法GetItems
public IQueryable<TEntity> GetItems(params Expression<Func<TEntity, object>>[] paths)
{
var dbSet = _dbSet as IQueryable<TEntity>;
if (paths != null)
foreach (var path in paths)
dbSet = dbSet.Include(path);
return dbSet;
}
dbSet返回的值:
如果出现dbset的值为:
{SELECT
[Extent1].[ID] AS [ID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[AdminId] AS [AdminId],
[Extent1].[Title] AS [Title],
[Extent1].[Summary] AS [Summary],
[Extent1].[Alias] AS [Alias],
[Extent1].[Content] AS [Content],
[Extent1].[ArticleShare] AS [ArticleShare],
[Extent1].[ArticleVisit] AS [ArticleVisit],
[Extent1].[ArticleReship] AS [ArticleReship],
[Extent1].[CreateTime] AS [CreateTime],
[Extent1].[Level] AS [Level],
[Extent2].[AdminId] AS [AdminId1],
[Extent2].[UserName] AS [UserName],
[Extent2].[PassWord] AS [PassWord],
[Extent2].[Nike] AS [Nike],
[Extent2].[Email] AS [Email],
[Extent2].[HeadImage] AS [HeadImage]
FROM [dbo].[Posts] AS [Extent1]
INNER JOIN [dbo].[Admins] AS [Extent2] ON [Extent1].[AdminId] = [Extent2].[AdminId]}
需要注意一下红字的部分
如果不是,出现[extent1].[admin_adminId]=[Extent2].[AdminId]
这样的值 就是因为类:Admin中出现了 public List<Post> Posts{get;set;}
这个属性了
一般情况下如果是一对多的关系
在多种添加一的id和实体类属性就可以了
譬如:Post中出现:AdminId 和Admin这两个属性就可以了
不必要在
Admin中添加List<post>属性
嘿嘿!!!