标签: entity-framework-5

在WebAPI控制器中序列化EF Code First 5.0数据时出错

我最初问过这个问题: 如何解决"指定的包含路径无效"?已经回答了,而我的.Include()现在正在工作,但是,当序列化程序试图使它变得神奇时,我收到以下错误:

You must write an attribute 'type'='object' after writing the attribute 
with local name '__type'.
Run Code Online (Sandbox Code Playgroud)

这是我正在做的返回数据:

var everything = dc.Categories
            .Include(c => c.Products);
Run Code Online (Sandbox Code Playgroud)

我的类定义相当简单:

public class Category
{
    public int CategoryId { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Title { get; set; }

    public virtual Category Category { get; set; }
} …
Run Code Online (Sandbox Code Playgroud)

ef-code-first asp.net-web-api entity-framework-5

7
推荐指数
1
解决办法
6788
查看次数

实体框架5中的LoadProperty

我将我的实体框架4.3数据库第一个项目升级到新的实体框架5. 显然我现在使用的是DbContext而不是ObjectContext.

我用新的.edmx文件替换了我的旧文件.我以前使用我的4.3 .edmx文件的旧业务代码现在使用该LoadProperty方法的代码存在问题:

using (var context = new MyEntities())
{
    Models.User user = context.Users.First(x => x.GUID == guid);
    context.LoadProperty(user, o => o.Settings);
    return user;
}
Run Code Online (Sandbox Code Playgroud)

似乎LoadProperty不是DbContext中的可用方法.

我怎么能得到强大的类型加载?

我想我可以使用

context.Users.Include("Settings")
Run Code Online (Sandbox Code Playgroud)

但这不是强类型,容易出现错别字.

c# asp.net entity-framework entity-framework-5

7
推荐指数
1
解决办法
5907
查看次数

在多对多链接表上有选择地禁用级联删除

是否可以在Entity Framework 5 Code First中自动生成的多对多链接表中有选择地删除Cascade Delete选项?这是一个需要它的简单示例:

public class Parent
{
    public int Id { get; set; }

    public virtual IList<ChildA> As { get; set; }
    public virtual IList<ChildB> Bs { get; set; }
}

public class ChildA
{
    public int Id { get; set; }
    [Required]
    public virtual Parent Parent { get; set; }

    public virtual IList<ChildB> ChildBJoins { get; set; }
}

public class ChildB
{
    public int Id { get; set; }
    [Required]
    public virtual Parent Parent { …
Run Code Online (Sandbox Code Playgroud)

entity-framework ef-code-first entity-framework-5

7
推荐指数
1
解决办法
1528
查看次数

在Entity Framework中使用计算的DateTime列

StoreGeneratedPattern="Computed"在类型的列上完美地工作timestamp.但是你不能将TimeStamp显示为人类可读的形式.

因此,您无法向用户显示"此行已被修改{TimeStamp}",因为您无法将SQL时间戳解析为DateTime.

现在我还可以为DateTime列创建计算列,这样我就不需要手动设置它了吗? myEntity.LastModification = DateTime.Now

更不用说它会非常容易出错,如果有些用户真的想做坏事,只需改变他的电脑时间.

c# datetime entity-framework calculated-columns entity-framework-5

7
推荐指数
1
解决办法
6244
查看次数

实体框架4.3与5.0更新差异

几个月以来,我一直在研究我的ASP.NET MVC应用程序.当我第一次开始使用它时,我使用的是Entity Framework 4.3(Code-First w/Migrations).当我这样做时,我遇到了一些问题,试图在我的MainClient表上进行更新.MainClient包含客户端的所有基本信息,与BPClient表具有1:1的关系,其中包含有关该客户端与BP模块的许可协议有关的更多特定信息.这两个都可以在选项卡控件中的同一页面上进行编辑.但是,在尝试将MainClient对象的EntityState更改为EntityState.Modified时,我一直收到以下异常:

System.InvalidOperationException : An object with the same key already exists 
in the ObjectStateManager. The ObjectStateManager cannot track multiple objects 
with the same key.
Run Code Online (Sandbox Code Playgroud)

我注意到在调试时,对象本身在进入我的Controller类进行保存时被认为是Detached.作为此问题的解决方法,我对此博客文章此SO问题中的问题应用了类似的解决方案.以下是在以下MainClient对象中传递Edit方法的情况下,重新附加对象的代码后来看起来如何(凌乱,我知道)client:

var newClientObject = new MainClient { ClientID = client.ClientID };
Db.MainClients.Attach(newClientObject);
Db.Entry(newClientObject).CurrentValues.SetValues(client);

var bpClient = new BPClient { ClientID = client.ClientID, BaseClient = newClientObject };
if (client.BPClient != null)
{
    Db.BostonpostClients.Attach(bpClient);
    Db.Entry(bpClient).CurrentValues.SetValues(client.BPClient);
}

Db.SaveChanges()
Run Code Online (Sandbox Code Playgroud)

在所有测试用例中,这都很好用.直到最近.

最近,我升级了我的应用程序以使用Entity Framework 5(仍然使用Code-First).不过,当我再次测试MainClient编辑页面时,我发现了一些相当不稳定的行为.编辑时,某些字段可以毫无问题地保存.其他人永远不会致力于数据库.还有一些会坚持下去,但前提是它们是被编辑对象的唯一部分.我调试了Controller类中的DbContext,并且非常烦人地发现,不仅在页面上发生的更改被发送到Controller类,而且ObjectStateManager同时包含MainClient和BPClient对象.它与页面上所做的更改一样!顺便提一下,我在这里应该提一下,在调试时我没有收到一个错误,甚至在SaveChanges()之后也没有.

我决定尝试将代码恢复到原来的状态,也就是说这样做的逻辑方式:

Db.Entry<BPClient>(client.BPClient).State = EntityState.Modified;
Db.Entry<MainClient>(client).State …
Run Code Online (Sandbox Code Playgroud)

.net entity-framework entity-framework-4 entity-framework-5

7
推荐指数
1
解决办法
2060
查看次数

实体框架5 - 实现SQL Server"以用户身份执行"

我正在使用带有Entity Framework 5和SQL Server 2008的Visual Studio 2012编写数据库应用程序.我希望Entity Framework能够模拟SQL Server用户(即没有登录的用户).我为DB上下文创建了一个新的构造函数,MyDatabaseEntities其中包含一个用于模拟的用户名的参数.这是我写的代码:

public partial class MyDatabaseEntities
{
    private String _impersonateUser = null;

    public MyDatabaseEntities(String impersonateUser)
        : base("MyConnectionString")
    {
        _impersonateUser = impersonateUser;

        this.Database.Connection.StateChange += Connection_StateChange;

    }

    void Connection_StateChange(object sender, StateChangeEventArgs e)
    {
        if (e.CurrentState == ConnectionState.Open && e.OriginalState != ConnectionState.Open)
        {
            using (var cmd = this.Database.Connection.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;

                cmd.Parameters.Add(new SqlParameter("user", _impersonateUser));

                cmd.CommandText = "EXECUTE AS USER = @user";

                cmd.ExecuteNonQuery();

            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

我不得不加上支票......

if (e.CurrentState == ConnectionState.Open && e.OriginalState != …
Run Code Online (Sandbox Code Playgroud)

impersonation sql-server-2008-r2 entity-framework-5 visual-studio-2012

7
推荐指数
1
解决办法
2294
查看次数

为什么在更新父项时实体框架会插入子项?

我在针对.Net 4.5的Windows服务中使用此代码,该服务使用数据库优先的Entity Framework层:

var existingState = DataProcessor.GetProcessState(workerId);

existingState.ProcessStatusTypeId = (int)status;
existingState.PercentProgress = percentProgress;
existingState.ProgressLog = log;

DataProcessor.UpdateProcessState(existingState);
Run Code Online (Sandbox Code Playgroud)

而这个代码在同一个解决方案中的数据处理类中:

public ProcessState GetProcessState(int id)
{
    using (var context = new TaskManagerEntities())
    {
        var processes = (from p in context.ProcessStates.Include("ProcessType").Include("ProcessStatusType")
                         where p.IsActive && p.ProcessStateId == id
                         select p);

        return processes.FirstOrDefault();
    }
}

public ProcessState UpdateProcessState(ProcessState processState)
{
    using (var context = new TaskManagerEntities())
    {
        context.ProcessStates.Add(processState);
        context.Entry(processState).State = System.Data.EntityState.Modified;
        context.SaveChanges();
    }

    return processState;
}
Run Code Online (Sandbox Code Playgroud)

ProcessState是另外两个类(ProcessStatusType和ProcessType)的父级.当我在Windows服务中运行该代码时,它会检索记录,更新实体并保存它.尽管ProcessType子元素从未在上面的代码中使用,但是当执行ProcessState实体上的保存时,EF会在ProcessType表上执行插入操作并在其中创建新记录.然后,它更改ProcessStatus实体中的FK,将其指向新子项并将其保存到数据库中.

它并没有在ProcessStatusType表,设置了基本相同的FK父子关系做到这一点.

我现在有一个完全相同的ProcessType条目的数据库,我不需要,我不知道为什么会这样.我觉得我犯了一些我无法看到的明显错误,因为这是我的第一个EF项目.问题是我允许上下文在调用之间到期但是保持相同的实体吗?

asp.net-mvc entity-framework windows-services asp.net-mvc-4 entity-framework-5

7
推荐指数
1
解决办法
4903
查看次数

如果使用实体连接字符串(与SQL连接字符串一起使用),ASP.NET MVC4简单成员身份无法初始化

我正在使用Entity Framework 5开发ASP.NET MVC4应用程序,我正在使用Model First模式.

但是,如果我使用设计器生成的连接字符串,则Simple Membership将引发以下错误:

    ......
  InnerException: System.InvalidOperationException
   HResult=-2146233079
   Message=The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588
   Source=STD
   StackTrace:
        at SistemTempahanDewan.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() in c:\Users\Orang\Documents\Visual Studio 2012\Projects\STD\STD\Filters\InitializeSimpleMembershipAttribute.cs:line 45
   InnerException: System.ArgumentException
        HResult=-2147024809
        Message=Unable to find the requested .Net Framework Data Provider.  It may not be installed.
        Source=System.Data
        StackTrace:
             at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
             at WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString)
    ....
Run Code Online (Sandbox Code Playgroud)

设计者生成的连接字符串(不起作用):

<add name="STD" connectionString="metadata=res://*/Models.STD.csdl|res://*/Models.STD.ssdl|res://*/Models.STD.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;initial catalog=STD;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
Run Code Online (Sandbox Code Playgroud)

连接字符串我手动添加(将工作):

<add name="STD" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=STD;Integrated Security=True;MultipleActiveResultSets=True" …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc-4 entity-framework-5

7
推荐指数
1
解决办法
2万
查看次数

在存储库模式中按ID过滤是不好的做法

我正在使用ASP.NET MVC4Entity Framework 5.

基本上每个控制器操作结果都按登录的用户公司ID过滤db结果.我刚刚开始实现一个存储库模式来返回模型,而不是直接从控制器中过滤DbContext.(将companyID传递到存储库以过滤方法的结果)

我有一种有趣的感觉,这样做是不好的做法,但一直无法找到有关该主题的任何信息.我将在下面插入我当前代码的基本版本,我将不胜感激任何关于它是否是不良做法的信息,以及为什么如此.

IBookingSystemRepository.cs

public interface IBookingSystemRepository : IDisposable
{
    IEnumerable<Appointment> GetAppointments();
    IEnumerable<Appointment> GetAppointments(bool includeDeleted);
    IEnumerable<Client> GetClients();
    IEnumerable<Client> GetClients(bool includeDeleted);
    void Save();
}
Run Code Online (Sandbox Code Playgroud)

BookingSystemRepository.cs

public class BookingSystemRepository : IBookingSystemRepository
{
    private BookingSystemEntities db;
    int CompanyID;

    public BookingSystemRepository(BookingSystemEntities context, int companyID)
    {
        this.db = context;
        this.CompanyID = companyID;
    }

    public IEnumerable<Appointment> GetAppointments()
    { return GetAppointments(false); }

    public IEnumerable<Appointment> GetAppointments(bool includeDeleted)
    {
        return includeDeleted
            ? db.Appointments.Where(a => a.User.CompanyID == CompanyID)
            : db.Appointments.Where(a => a.User.CompanyID …
Run Code Online (Sandbox Code Playgroud)

.net c# entity-framework asp.net-mvc-4 entity-framework-5

7
推荐指数
1
解决办法
1307
查看次数

EF5 DbContext.SaveChanges是否处理事务提交和回滚?

我不清楚我是否需​​要使用TransactionScope或DbContext.SaveChanges()足以提交由多个CRUD操作组成的事务.我在后端使用SQL Server.

entity-framework transactionscope dbcontext entity-framework-5

7
推荐指数
1
解决办法
4943
查看次数