我希望以某种方式编写实体框架或 LINQ to SQL 查询,以便当我在 SQL Server Profiler 中看到 SQL 查询时,我可以快速识别哪个 LINQ 语句生成该 SQL,而无需进入调试器并跟踪它。该应用程序不会使用存储过程,这使得通过过程名称进行搜索变得容易。
有任何想法吗?有没有一种方法可以在 LINQ 查询中注入带有代码的静态字符串,仅用于识别查询而不影响查询结果?
更新
我添加此内容是为了响应日志记录建议。我不想在生产中一直运行日志记录,以防出现问题时需要查看某些 SQL。寻找一种性能成本最小的方法。向每个 linq 语句附加一些唯一的字符串,以便代码可以很容易地与 SQL 相关联?
我正在与C#, .NET4.5, EF6(实际上应该不重要)。
我从数据库中选择一些值,然后.ToList()添加它们,DefaultIfEmpty(new ActualFee{Net = 0, Vat = 0})如果不存在则添加,然后我得到null
public static ConveyancingSummaryVm ToConveyancingSummaryVm(this Tuple<IEnumerable<ActualFee>, ConveyancingAnswer, Customer> conveyancePricingAnswersAndCustomer)
{
var purchaseFees = conveyancePricingAnswersAndCustomer.Item1.Where(o => o.ConveyancingSaleType == "Purchase").ToList();
if (purchaseFees.Any())
{
var discount = purchaseFees.DefaultIfEmpty(new ActualFee{Net = 0, Vat = 0}).SingleOrDefault(o => o.Title.Contains("Discount"));
conveyancingSummaryVm.IsPurchaseFreehold = conveyancePricingAnswersAndCustomer.Item2.PropertyBoughtIsFreehold;
...
Run Code Online (Sandbox Code Playgroud)

我一定在这里遗漏了一些明显的东西。
我尝试将两个存储过程(仅从视图返回数据)添加到 EDMX 文件。但完成向导后,存储过程不会显示在设计器中。我完全陷入困境,无法理解为什么存储过程没有添加到设计器中。将存储过程添加到 EDMX 是否有任何限制?
我正在使用 Visual Studio 2013、Entity Framework 6.1 和 SQL Server 2012
我有一个博客应用程序,用户可以创建帖子,我使用实体框架从数据库创建模型。在帖子中我有一个条目UrlSlug。
但是,当我检查帖子的详细信息时:
控制器:
public ActionResult Details(int id = 0)
{
Post post = db.Posts.Find(id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
Run Code Online (Sandbox Code Playgroud)
id它返回一个末尾带有以下内容的 url :http://localhost:52202/Post/Details/1
我尝试返回 post.UrlSlug (引发错误)以及更改我的 RouteConfig.cs 文件来使用urlslug(id它确实显示 urlslug,但由于控制器而无法找到页面)。如何更改此设置以便显示 urlslug 而不是 Post Table Id?
路由配置.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
看法:
@for (int i …Run Code Online (Sandbox Code Playgroud) 我有以下 linq 查询:
Var q1 = (from t1 in context.Table1
where column = value
select t1).FirstOrDefault();
Var q2 = (from t2 in context.Table2
where column = value
select t2).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
据我了解,上述linq语句将调用database两次来获取表数据,但我想linq以这种方式编写查询以在单个数据库调用中获取两个表数据。我怎样才能实现这个目标?
我有下表,我需要一个查询,将 roleId 值分组到一个列表中并将其放入 DTO 中。示例和预期结果如下表所示。
我知道它不应该是复杂的东西,但我不知道如何......我浏览了一些示例,我只找到了它们处理分组内容的计数而不是它们的列表的示例。
+----+--------+--------+
| id | userId | roleId |
+----+--------+--------+
| 1 | 1 | 1 |
+----+--------+--------+
| 2 | 1 | 2 |
+----+--------+--------+
| 3 | 2 | 1 |
+----+--------+--------+
Run Code Online (Sandbox Code Playgroud)
public class UserRoleDto
{
public int userId { get; set; }
public List<int> roleIds { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
预期结果:
var res = new List<UserRoleDto>
{
new UserRoleDto()
{
userId = 1,
roleIds = new List<int>() {1, 2}
},
new UserRoleDto() …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个搜索函数,我可以在其中传递一个 Func ,该函数允许我指定要搜索的字符串属性。实体框架 6 抱怨我正在尝试调用一个函数,这是不允许的。有没有办法重写以下内容以便我可以将其与 EF 一起使用?
public List<Person> SearchPeople(string searchTerm, Func<Person, string> selector)
{
return myDbContext.Persons.Where(person => selector(person).Contains(searchTerm)).ToList();
}
Run Code Online (Sandbox Code Playgroud)
LINQ to Entities 不支持 LINQ 表达式节点类型“Invoke”。
我正在尝试将外键添加到数据库,然后更新模型。更新模型后,应用程序出现以下错误:
System.Data.Entity.Core.MetadataException was unhandled
HResult=-2146232007
Message=Schema specified is not valid. Errors:
The relationship 'Accounting.Data.Repository.FK_np_DocumentStatuses_DocumentsTracking_StateId' was not loaded because the type 'Accounting.Data.Repository.DocumentsTracking' is not available.
The following information may be useful in resolving the previous error:
The required property 'DocumentsTrackingChildDocuments' does not exist on the type 'Accounting.Entity.DocumentsTracking'.
The relationship 'Accounting.Data.Repository.FK_np_DocumentsTracking_DocumentsTrackingChildDocuments_DocumentsTrackingId' was not loaded because the type 'Accounting.Data.Repository.DocumentsTracking' is not available.
The following information may be useful in resolving the previous error:
The required property 'DocumentsTrackingChildDocuments' does not exist on the type …Run Code Online (Sandbox Code Playgroud) 我收到的错误消息如下 ----- MVCRegistration.Models.Post_UserProfile: : 多重性与关系“Post_UserProfile”中角色“Post_UserProfile_Target”中的引用约束冲突。由于从属角色中的所有属性均不可为空,因此主体角色的重数必须为“1”。MVCRegistration.Models.PostComment_UserProfile::多重性与关系“PostComment_UserProfile”中角色“PostComment_UserProfile_Target”中的引用约束冲突。由于从属角色中的所有属性均不可为空,因此主体角色的重数必须为“1”。 这里,MVCRegistraion 是解决方案文件名。
现在,我有这样的三堂课——
public class UserProfile
{
public UserProfile()
{
this.PostComments = new HashSet<PostComment>();
this.Posts = new HashSet<Post>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string AvatarExt { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
后期课程是这样的----
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int …Run Code Online (Sandbox Code Playgroud) 当使用 Linq 和 Entity Framework 来查询数据库时,有没有办法减少重复的 lambda?例如:
db.Users.FirstOrDefault(x => x.Username == "MM001" && x.Type == 1 && x.IsActive == True && x.ExpiryDate > DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
我想把它变成:
db.Users.FirstOrDefault(x => x.Username == "MM001" && x.IsActiveStaff());
Run Code Online (Sandbox Code Playgroud)
我尝试在我的 Users POCO 中编写如下方法:
public bool IsActiveStaff()
{
return Type == 1 && IsActive == True && ExpiryDate > DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:LINQ to Entities 无法识别方法“Boolean IsActiveStaff()”方法,并且此方法无法转换为存储表达式。
我意识到这是因为 LINQ To Entities 无法将此方法转换为 SQL 表达式,但是有什么方法可以让它工作吗?
我知道我可以编写一个查询命令类,它只需将用户名作为参数,并将所有逻辑放在其中,但我想知道是否可以将一系列 lambda 嵌入到方法或扩展方法等中,并在需要时使用它们,就像我上面的示例一样。
entity-framework ×10
c# ×8
linq ×7
.net ×2
asp.net-mvc ×2
linq-to-sql ×2
c#-4.0 ×1
lambda ×1
one-to-many ×1
sql ×1