如何用IObjectSet初始化这个代码?

时间:2010-11-24 15:31:09

标签: c# entity-framework-4

我有这段代码:

public interface IEntityBase<T> where T : struct, IComparable
{
    T? ID { get; set; }
}

public class EntityBase<T> : IEntityBase<T> where T : struct, IComparable
{
    private T? _id;

    protected EntityBase(T? key)
    {
        this._id = key;
    }

    public virtual T? Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public override bool Equals(object entity)
    {
        if (entity == null || !(entity is EntityBase<T>))
        {
            return false;
        }

        return (this == (EntityBase<T>)entity);
    }

    public static bool operator ==(EntityBase<T> left, EntityBase<T> right)
    {
        if ((object)left == null && (object)right == null)
        {
            return true;
        }

        if ((object)left == null || (object)right == null)
        {
            return false;
        }

        if (left.Id.Value.CompareTo(right.Id.Value) != 0)
        {
            return false;
        }

        return true;
    }

    public static bool operator !=(EntityBase<T> left, EntityBase<T> right)
    {
        return (!(left == right));
    }

    public override int GetHashCode()
    {
        return this._id.HasValue ? this._id.Value.GetHashCode() : 0;
    }
}

,MyContext代码:

但在ObjectSet函数中,出现错误消息!

什么是正确的语法?

public class MyContext : ObjectContext
{
    private IObjectSet<Page> _pageSet;

    public MyContext(EntityConnection connection)
        : base(connection)
    {
    }

    public IObjectSet<Page> PageSet
    {
        get
        {
            return _pageSet ?? (_pageSet = ObjectSet<Page>());
        }
    }

    public virtual IObjectSet<TEntity> ObjectSet<TEntity>() where TEntity : struct, EntityBase<TEntity>, IComparable
    {
        return CreateObjectSet<TEntity>();
    }
}

班级页面:

public class Page : EntityBase<long>
{
    public Page(long? key)
        : base(key)
    {
    }

    public virtual string Title { get; set; }
    public virtual string Body { get; set; }
    public virtual Page Parent { get; set; }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

这一行:

public virtual IObjectSet<TEntity> ObjectSet<TEntity>() 
                where TEntity : struct, EntityBase<TEntity>, IComparable

您指定TEntity必须是struct 并且是引用类型(EntityBase<>是一个类,因此是引用类型)。这些是相互排斥的。你可能想要的(没有看到CreateObjectSet很难说)是:

public virtual IObjectSet<TEntity> ObjectSet<TEntity, T>() 
                where TEntity : EntityBase<T>
                where T : struct, IComparable

请注意,这只是基于您的其他代码的猜测,但主要问题是您尝试将通用参数限制为结构和类,并且您需要修复它。

答案 1 :(得分:0)

您没有指定要获得的错误类型...请确保您正在构建定位4.0 Framework ...