gpt4 book ai didi

entity-framework - Entity Framework 4.1 无效的列名

转载 作者:行者123 更新时间:2023-12-04 01:45:24 24 4
gpt4 key购买 nike

我有两个表 News 和 NewsComments。我遵守命名规则

结构新闻评论

public class NewsComment : BaseComment
{
public int NewsId { get; set; }

public virtual News News { get; set; }
}

但查询返回异常无效的列名“News_Id”。我知道这个异常在表中不相关的列中创建了什么。
CREATE TABLE [dbo].[NewsComments](
[Id] [int] IDENTITY(1,1) NOT NULL,
[NewsId] [int] NOT NULL,
[Text] [varchar](max) NOT NULL,
[UserId] [int] NOT NULL,
[CommentDate] [datetime] NOT NULL,
[Ip] [varchar](40) NOT NULL, CONSTRAINT [PK_NewsComments] PRIMARY KEY CLUSTERED([Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

基础评论
public abstract class BaseComment : BasePersistentEntity, IComment
{

public int UserId { get; set; }

public virtual BaseUser User { get; set; }

[Display(ResourceType = typeof(FrameworkResurce), Name = "CommentText")]
public string Text { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "CommentDate")]
public DateTime CommentDate { get; set; }


public string Ip { get; set; }
}

新闻
public class News : BaseContent
{
[Display(ResourceType = typeof(NewsResurce), Name = "NewsImage")]
public string NewsImage { get; set; }

public virtual ICollection<NewsCommentView> CommentViews { get; set; }
}

基本内容
public abstract class BaseContent : BasePersistentEntity
{
[Display(ResourceType = typeof(FrameworkResurce), Name = "Keywords")]
public string Keywords { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "TitleTranslit")]
public string TitleTranslit { get; set; }

[Required(ErrorMessageResourceType = typeof(FrameworkResurce), ErrorMessageResourceName = "IsTextEmpty")]
[Display(ResourceType = typeof(FrameworkResurce), Name = "Title")]
public string Title { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "Description")]
public string Description { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "Contents")]
public string Contents { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "DatePublish")]
public DateTime DatePublish { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "AuthorPublish")]
public string AuthorPublish { get; set; }

[Display(ResourceType = typeof(FrameworkResurce), Name = "Author")]
public string Author { get; set; }

[Display(ResourceType = typeof(FrameworkResurce), Name = "AuthorUrl")]
public string AuthorUrl { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "Views")]
public int Views { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "Comments")]
public int Comments { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "IsComment")]
public bool IsComment { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "SumVote")]
public int SumVote { get; set; }


[Display(ResourceType = typeof(FrameworkResurce), Name = "VoteCount")]
public int VoteCount { get; set; }

[NotMapped]
[Display(ResourceType = typeof(FrameworkResurce), Name = "Rating")]
public double Rating
{
get
{
if (VoteCount > 0)
{
return Math.Round((float)SumVote/VoteCount, 2);
}

return 0;
}
}
}

查询
private IEnumerable<NewsComment> GetComments()
{
var news = NewsCommentRepository.AllIncluding(c=>c.User,c=>c.News);
return news;
}

private DataRepository<NewsComment> NewsCommentRepository
{
get { return DataRepository<NewsComment>.Repository; }
}

数据存储库
public class DataRepository<T> where T : BasePersistentEntity
{
public static DataRepository<T> Repository
{
get
{
return new DataRepository<T>();
}
}

private readonly SGNContext<T> context = new SGNContext<T>();

public IQueryable<T> All
{
get { return this.context.Table; }
}

public IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = this.context.Table;
return includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
}

public T Find(int id)
{
return this.context.Table.Find(id);
}

public void InsertOrUpdate(T country)
{
if (country.Id == default(int))
{
// New entity
this.context.Table.Add(country);
Save();
}
else
{
// Existing entity
this.context.Entry(country).State = EntityState.Modified;
Save();
}
}

public void Delete(int id)
{
var country = this.context.Table.Find(id);
this.context.Table.Remove(country);
this.Save();
}

private void Save()
{
this.context.SaveChanges();
}
}

在哪里使用 GetComments
    [GridAction]
public ActionResult AjaxCommentsBinding()
{
return View(new GridModel<NewsComment>
{
Data = GetComments()
});
}

新闻评论浏览次数
CREATE VIEW [dbo].[NewsCommentViews]
AS
SELECT dbo.NewsComments.NewsId, dbo.NewsComments.Text, dbo.NewsComments.UserId, dbo.NewsComments.CommentDate, dbo.NewsComments.Ip,
dbo.Roles.RoleName, dbo.Users.UserName, dbo.Users.DateRegistered, dbo.NewsComments.Id, dbo.Users.Avatar
FROM dbo.NewsComments INNER JOIN
dbo.Users ON dbo.NewsComments.UserId = dbo.Users.Id INNER JOIN
dbo.Roles ON dbo.Users.RoleId = dbo.Roles.Id

新闻评论浏览次数
[Table("NewsCommentViews")]
public class NewsCommentView : NewsComment
{
public string RoleName { get; set; }

public string UserName { get; set; }

public DateTime DateRegistered { get; set; }

public string Avatar { get; set; }
}

最佳答案

问题在于News之间的关系和 NewsCommentView : 关系的一端是News.CommentViews收藏。但另一端是不是 NewsCommentView.News正如您所期望的那样。为什么?因为属性(property)News不是 声明 NewsCommentView类但在基类 NewsComment .现在 EF 不允许实体参与具有不是 的导航属性的关系。声明 在该实体类本身上,但仅在基类中。

因此,因为您没有 Fluent 映射,所以 EF 仅按约定定义所有关系。发生什么了?

  • News有导航属性 CommentViews声明并指向 NewsCommentView类(class)。
  • EF 未找到类型为 News 的逆属性这是 声明 NewsCommentView类(class)。 (有一个,但它在基类中,这不算数。)
  • 因此,EF 假设关系的另一端是 未曝光 NewsCommentView类(class)。
  • 未公开意味着:EF 没有导航属性也没有外键属性,并且将假定数据库表/ View 中必要的外键列NewsCommentViews将有一个标准的约定名称。
  • 这个约定俗成的名字是 NameOfEntityClass_PKPropertyName -> News_Id

  • 您在 View 中的真实姓名是 NewsId尽管。因此,EF 查询列 News_Id不存在,因此异常(exception)。

    当你的MVC-View访问 NewsComment.News.CommentViews时,该异常可能是由于延迟加载而触发的。 .

    您可以通过在 Fluent API 中明确指定 FK 列名来解决此问题(据我所知,没有 Fluent 映射就没有其他方法):
    public class MyContext : DbContext
    {
    // ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Entity<News>()
    .HasMany(n => n.CommentViews)
    .WithRequired() // <- no param because not exposed end of relation,
    // nc => nc.News would throw an exception
    // because nc.News is in the base class
    .Map(a => a.MapKey("NewsId"));
    }
    }

    但是 小心 : 请注意 NewsCommentView.News不是 属于 News.CommentViews的关系的另一端.这意味着如果您有 NewsCommentView在您的 News.CommentViews然后收藏 NewsCommentView.News 不是 回到那个 News目的。另一端是不可见的,不会暴露在模型中。上面的映射只是修复了 FK 列名问题,但不会改变约定会创建的关系(除非可能将关系更改为必需而不是可选)。

    关于entity-framework - Entity Framework 4.1 无效的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055962/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com