如何为Linq To Sql生成正确的SQL?

时间:2012-03-11 16:29:07

标签: c# entity-framework linq-to-sql

我使用LinqToSql根据当前用户权限按对象状态从数据库中收集一些数据。我使用这样的扩展名:

Context.Object1.ByActiveStatus();
Context.Object2.ByActiveStatus();

我现在有以下实施方案,效果很好。

public class Object1{
    public string Status {get;set;} //generated by Visual Studio (simplified version)
    public Guid? CreatedBy {get;set;} //generated by Visual Studio (simplified version)
    public Guid? LastUpdatedBy {get;set;} //generated by Visual Studio (simplified version)
}
public class Object2{
    public string Status {get;set;} //generated by Visual Studio (simplified version)
    public Guid? ModifiedBy {get;set;} //generated by Visual Studio (simplified version)
}

//extensions in separate static class
public static IQueryable<Object1> ByActiveStatus(this IQueryable<Object1> rep)
{
    return CurrentUser.IsAdmin 
        ? rep
        : rep.Where(ch=>ch.Status == "Active"
            || ch.CreatedBy == CurrentUser.CurrentUserId
            || ch.LastUpdatedBy == CurrentUser.CurrentUserId)           
}

public static IQueryable<Object2> ByActiveStatus(this IQueryable<Object2> rep)
{
    return CurrentUser.IsAdmin 
        ? rep
        : rep.Where(ch=>ch.Status == "Active"
            || ch.ModifiedBy == CurrentUser.CurrentUserId)
}

我想用这样的东西转换它。

public class Object1:IActiveStatus{
    public string Status {get;set;} //generated by Visual Studio (simplified version)
    public int CreatedBy {get;set;} //generated by Visual Studio (simplified version)
    public int LastUpdatedBy {get;set;} //generated by Visual Studio (simplified version)
}
public partial class Object1:IActiveStatus{
    public IEnumerable<Guid?> GetModifiedBy(){
        yield return CreatedBy;
        yield return LastUpdatedBy;
    }
}
public class Object2:IActiveStatus{
    public string Status {get;set;} //generated by Visual Studio (simplified version)
    public int ModifiedBy {get;set;} //generated by Visual Studio (simplified version)
}
public partial class Object2:IActiveStatus{
    public IEnumerable<Guid?> GetModifiedBy(){
        yield return ModifiedBy;
    }
}

public interface IActiveStatus{
    string Status{get;set;}
    IEnumerable<Guid?> GetModifiedBy();
}

public static IQueryable<T> ByActiveStatus<T>(this IQueryable<T> rep) where T:IActiveStatus
{
    return CurrentUser.IsAdmin 
        ? rep
        : rep.Where(ch=>ch.Status == "Active"
            || ch.GetModifiedBy().Any(c=>c.Value.Equals(CurrentUser.CurrentUserId)));
}

此解决方案不起作用,因为LinqToSql无法正确地将GetModifiedBy()方法转换为SQL。 如何正确生成sql:

  1. 实施需要什么(自定义提供商或什么?)?
  2. 尽可能的样本

1 个答案:

答案 0 :(得分:0)

   public IEnumerable<string> GetModifiedBy(){
        yield return CreatedBy{get;set;}
        yield return LastUpdatedBy{get;set;}
    }

这是非常奇怪的构造,几乎无法编译。

  1. 签名中有string,但会产生int s
  2. 更正确的方法似乎是yield return CreatedBy.ToString();
  3. 你试过吗?

       public IEnumerable<int> GetModifiedBy(){
            yield return CreatedBy;
            yield return LastUpdatedBy;
        }