相关疑难解决方法(0)

检查实体框架中是否存在实体的一般方法?

类似于检查实体框架中是否存在对象的最佳方法?

我正在寻找一种通用的方法来检查一个实体DbSet.像这样的东西,这是行不通的:

private DbContext DbContext { get; set; }

private DbSet<T> DbSet { get; set; }

public Boolean Exists(T entity) {
    return ((from item in this.DbSet
             where item == entity
             select item).Count() > 0);
}
Run Code Online (Sandbox Code Playgroud)

该行where item == entity适用于LINQ to SQL,但显然不适用于LINQ to Entities.由于实体可能具有不同的密钥,因此我们不能将它们全部继承自具有已知密钥的公共抽象以进行比较.

我可以做到这一点,但我担心将异常作为验证过程的表现这也不起作用,因为只要实体被分离,OriginalValues就无法获得属性:

public Boolean Exists(T entity) {
    try {
        var current = this.DbContext.Entry(entity).OriginalValues;
        // Won't reach this line if the entity isn't in the database yet
        return true;
    }
    catch …
Run Code Online (Sandbox Code Playgroud)

c# generics entity-framework-4.1

57
推荐指数
2
解决办法
6万
查看次数

首先是实体框架代码.查找主键

如何找到类的哪个属性是实体框架代码优先实体POCO的主键?

请注意Id/class name +"Id"的字符串匹配是一个不好的选择.必须有一些方法来挖掘Entity Framework使用的约定并可靠地获取密钥属性.

提前致谢.

ef-code-first entity-framework-4.1

33
推荐指数
4
解决办法
2万
查看次数

实体框架4:如何找到主键?

我正在尝试使用EF4创建一个通用方法来查找对象的主键.

public string GetPrimaryKey<T>()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

为了提供更多信息,我正在使用Tekpub StarterKit,下面是我试图启动和运行的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Objects.ELinq;
using System.Data.Linq;
using Web.Infrastructure.Storage.EF4;

namespace Web.Infrastructure.Storage {
public class EFSession:ISession {
    PuzzleEntities _db;//This is an ObjectContext
    public EFSession() {
        _db = new PuzzleEntities();
    }

    public void CommitChanges() {
        _db.SaveChanges();
    }
    /// <summary>
    /// Gets the table provided by the type T and returns for querying
    /// </summary>
    private ObjectSet<T> GetObjectSet<T>() where T:class {
        return _db.CreateObjectSet<T>();
    }

    private T …
Run Code Online (Sandbox Code Playgroud)

.net c# entity-framework primary-key entity-framework-4

13
推荐指数
3
解决办法
3万
查看次数