我有以下代码
var dates = query.Select(
x => DateTime.ParseExact(x.Date, "yyyy-MM", CultureInfo.InvariantCulture));
var minDate = dates.Min(x => x);
Run Code Online (Sandbox Code Playgroud)
但是当我执行它时,我得到了异常
System.Data.Entity.dll 但未在用户代码中处理
其他信息:LINQ to Entities 无法识别“System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)”方法,并且此方法无法转换为存储表达式。
我究竟做错了什么?我该如何解决这个问题?
我已阅读与此相关的所有帖子,并且已尝试所有内容,但没有结果。
我使用 Fluent api 将我的模型映射到数据库。但是当我查询时我收到此错误:
Method not found:
'System.Data.Entity.ModelConfiguration.Configuration.DecimalPropertyConfiguration
System.Data.Entity.ModelConfiguration.Configuration.DecimalPropertyConfiguration.HasDatabaseGeneratedOption(System.Nullable`1<System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption>)'.
Run Code Online (Sandbox Code Playgroud)
我的模型看起来像这样:
ToTable("table_name");
HasKey(x => x.CounterId)//this property IS NOT NULLABLE
.Property(x => x.CounterId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("dbCounter_Id")
.HasPrecision(10, 0)
.IsRequired();
Property(x => x.HouseId)
.HasColumnName("dbHouseId");
Property(x => x.ApplicationId)
.HasColumnName("dbApplication_id");
Run Code Online (Sandbox Code Playgroud)
由于某种原因.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)给了我这个错误,所以当我退出它时:
HasKey(x => x.CounterId)
.Property(x => x.PageId)
.HasColumnName("dbCounter_Id")
.HasPrecision(10, 0)
.IsRequired();
Run Code Online (Sandbox Code Playgroud)
我没有收到错误,但我很幸运,当我尝试向该表添加记录时,我收到插入身份异常。我既不能添加也不能退出该HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)方法。
重要提示:键CounterId不是 INTEGER 类型,而是 DECIMAL(10,0)。这可能是这里的问题吗?我无法更改列的数据类型,因为生产中的许多应用程序都会受到最坏的影响。
希望我能得到任何帮助。
我正在尝试将 UOW 容器注入到 WebApi 2 actionfilter 属性中
public class VerifyApiToken : ActionFilterAttribute
{
[Inject]
public IUOW Uow { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
//get and save data to any repository in the uow container
base.OnActionExecuting(actionContext);
}
Run Code Online (Sandbox Code Playgroud)
UOW 容器按照预期进行注入,并且在第一个请求时一切正常。在后续请求中,EF 抛出异常,表明 DbContext 已被释放。
所有依赖项都绑定在请求范围内,因此底层 dbcontext 被释放是正常的。在 WebApi 控制器中使用构造函数注入时,一切正常,在每个请求上都会重新创建资源,为什么在尝试在 ActionFilterAttributes 中使用属性注入时不重新创建资源,如何解决这个问题?
我正在使用的 IFilterProvider:
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
IEnumerable<FilterInfo> controllerFilters = actionDescriptor.ControllerDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Controller));
IEnumerable<FilterInfo> actionFilters = actionDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Action));
IEnumerable<FilterInfo> filters = …Run Code Online (Sandbox Code Playgroud) asp.net entity-framework dependency-injection ninject asp.net-web-api
例如,我想尝试这样的事情。排序部分可能没有、1 个或多个按不同顺序排序的列。但我无法使用该ThenBy方法,因为它仅在OrderBy. 下面的代码将不断将顺序重置为排序列表中的最后一项。我也不想更改方法签名。非常感谢您的帮助,谢谢。
public IQueryable<Person> FilterList(string forename, List<Sorting> sorting)
{
IQueryable<Person> query = dc.Set<Person>();
if(!string.IsNullOrEmpty(forename)){
query = query.Where(w=>w.Forename.Contains(forename));
foreach(var sort in sorting)
{
switch(sort.By)
{
case "asc":
switch(sort.Sort)
{
case "forename":
query = query.OrderBy(o=>o.Forename);
break;
case "surname":
query = query.OrderBy(o=>o.Surname);
break;
}
break;
case "desc":
switch(sort.Sort)
{
case "forename":
query = query.OrderByDescending(o=>o.Forename);
break;
case "surname":
query = query.OrderByDescending(o=>o.Surname);
break;
}
break;
}
}
return query;
}
public class Sorting
{
public string Sort{get;set;}
public string By{get;set;} …Run Code Online (Sandbox Code Playgroud) A network-related or instance-specific error occurred while establishing a connection to SQL Server
Run Code Online (Sandbox Code Playgroud)
主页加载正常,但当我尝试转到帐户/注册或帐户/登录时出现错误。
文件 Filters/InitializeSimpleMembershipAttribute.cs 中的 SimpleMembershipInitializer 构造函数中的这一行发生错误
if (!context.Database.Exists())
Run Code Online (Sandbox Code Playgroud)
现在,如果我将 web.config 设置为
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" />
</entityFramework>
Run Code Online (Sandbox Code Playgroud)
它仅在本地工作,但我假设它使用本地数据库。现在我的 web.config 中的实体框架看起来像
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
Run Code Online (Sandbox Code Playgroud)
我有另一个应用程序,我使用相同的托管服务和免费数据库(appharbor 和 SQL Server Yocto),它工作得很好。我最近设置了一个新的应用程序和数据库,但它不起作用。我可以在 SQL Server 中很好地连接到数据库,并在 Visual Studio 2012 中扩展 DataConnections -> MyContextName,所以我知道连接字符串不是问题。
我想知道托管数据库的服务器是否存在问题,而我无权访问该服务器。
我对如何解决这个问题完全没有想法。谢谢。
这里有很多关于 EF 的文章需要很长时间才能保存,但我浏览了它们并使用了他们的答案,但似乎仍然得到非常慢的结果。
我的代码看起来像这样:
using (MarketingEntities1 db = new MarketingEntities1())
{
//using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
//{
int count = 0;
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.ValidateOnSaveEnabled = false;
while (count < ranges.Count)
{
if (bgw != null)
{
bgw.ReportProgress(0, "Saving count: " + count.ToString());
}
db.Set<xGeoIPRanx>().AddRange(ranges.Skip(count).Take(BATCHCOUNT));
db.SaveChanges();
count+=BATCHCOUNT;
}
//trans.Commit();
//}
}
Run Code Online (Sandbox Code Playgroud)
每个批次需要 30 秒以上才能完成。BatchCount 是 1000。我知道 EF 并没有那么慢。你可以看到我已经停止使用事务,我已经取消了跟踪,但这些似乎都没有帮助。
更多信息:
xGeoIpRanx 是一个空表,没有 PK(我不确定它会有多大帮助)。我正在尝试插入大约 1000 万个范围。
编辑:
我觉得很愚蠢,但我尝试使用bulkInsert,但我不断收到此实体不存在的错误,我查看了这段代码
using (var ctx = GetContext())
{
using (var transactionScope = new TransactionScope())
{
// …Run Code Online (Sandbox Code Playgroud) 数据库中有 2 张表,一张是 [PARENTS],另一张是 [CHILDREN] - 有 ParentId 作为外键。
所以父母和孩子之间的关系是一对多的。
问题是当我尝试创建一个新的 CHILDREN 记录时,它也会创建一个新的 PARENT 记录。
怎么解决呢?谢谢

public void Add(Model.Pages.PageGroup entity)
{
using (var ctx = new SmartDbContext())
{
var dbEntity = entity.ToEntity();
ctx.PageGroups.Add(dbEntity);
ctx.SaveChanges();
}
}
namespace SmartECM.Repository.EF
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class PageGroup
{
public PageGroup()
{
Pages = new HashSet<Page>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid GroupId { get; set; }
[Required]
[StringLength(100)]
public string GroupName { get; set; } …Run Code Online (Sandbox Code Playgroud) 我使用 C# 使用“从数据库生成”生成了数据库模型。POCO 类和上下文是使用 T4 模板生成的。一切工作正常,应用程序能够编辑、插入等,但我无法覆盖实体类中的 SaveChanges 方法。我需要这样做来添加业务逻辑。这是上下文类:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebApplication1
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class IInvoiceEntities2 : DbContext
{
public IInvoiceEntities2 ()
: base("name=IInvoiceEntities2 ")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
\n\ninternal static IQueryable<UserModel> SelectUser(this IQueryable<User> query, bool getChildren) {\n log.DebugFormat("create the select statement for an individual user {0}", getChildren ? "with children" : "without children");\n var res = query.Select(u => new UserModel {\n // [...] unimportant stuff\n Groups = u.Groups.Select(g => new GroupModel {\n Name = g.Name,\n Description = g.Description,\n ID = g.ID\n }).Take(10),\n CreatedGroups = !getChildren ? null : u.CreatedGroups.Select(g => new GroupModel {\n Name = g.Name,\n Description = g.Description,\n ID = g.ID\n }).Take(10)\n // [...] more …Run Code Online (Sandbox Code Playgroud) 有件事让我很困惑。我认为 EF 选择表中的所有行(所有记录)。
让我给你看一个样本。
public Category GetByID(int Id)
{
return context.Categories.Find(Id);
}
Run Code Online (Sandbox Code Playgroud)
表中有很多记录,当我用断点检查它们时,我可以看到所有记录,而不仅仅是 ID 编号为 1 的记录。如果表中有10k条记录怎么办?我测试这个。我手动复制了数据库中的所有记录,并创建了 30k 条记录。
像这样的表情,
IEnumerable<Category> categories = categoryRepository
.Where(x => x.Published == true)
.ToList();
Run Code Online (Sandbox Code Playgroud)
我看到有 30k 条带有断点的记录。但表中至少有 10k 已发布 False。
实体框架是否首先将所有记录提取到内存中,然后过滤它们?
entity-framework ×10
c# ×7
linq ×3
asp.net ×2
sql-server ×2
appharbor ×1
asp.net-mvc ×1
datetime ×1
ninject ×1
sql ×1
sql-order-by ×1