博客 (18)

使用 Linq 语法调用数据库时,需要包含导航属性(外键表数据)会用到 Include 方法,但是如果引用的程序集搞错了,就不会有数据输出,应该:

using Microsoft.EntityFrameworkCore;

而不是

using System.Data.Entity;

xoyozo 12 天前
83

语言集成查询(LINQ)为 C# 和 VB 提供语言级查询功能和高阶函数 API,让你能够编写具有很高表达力度的声明性代码。

LINQ 有两种写法:查询语法和方法语法,查询语法又称查询表达式语法。

查询语法:

from 变量名 in 集合 where 条件 select 结果变量

方法语法:

集合.Where(变量名 => 条件)


LINQ 的标准查询运算符及语法示例

类型操作符功能方法语法查询语法
投影操作符Select用于从集合中选择指定的属性或转换元素
cats.Select(cat => cat.color)
from cat in cats
select cat.color
SelectMany用于在嵌套集合中选择并平铺元素
families.SelectMany(family => family.members
.Select(member => member.name))
from family in families
from member in family.members
select member.name
限制操作符Where根据指定的条件筛选集合中的元素
cats.Where(cat => cat.color == "white")
from cat in cats
where cat.color == "white"
select cat
排序操作符

OrderByOrderByDescending、ThenBy、ThenByDescending

用于对集合中的元素进行排序
cats.OrderBy(cat => cat.age)
from cat in cats
order by cat.age
select cat
Reverse将集合中的元素顺序反转
cats.Reverse()


联接操作符

Join

GroupJoin

用于在两个集合之间执行内连接(Join)操作,或者对一个集合进行分组连接(GroupJoin)操作内联接
families.Join(
    members,
    family => family.familyId,
    member => member.familyId,
    (family, member) => new
    {
        family.familyId,
        member.name,
    })

左连接

families.GroupJoin(
    members,
    family => family.familyId,
    member => member.familyId,
    (family, familyMembers) => new
    {
        family.familyId,
        name = familyMembers.FirstOrDefault()?.name
    })


内联接
from family in families
join member in members on family.familyId equals member.familyId
select new
{
    family.familyId,
    member.name,
}

左连接

from family in families
join member in members on family.familyId equals member.familyId into g
from member in g.DefaultIfEmpty()
select new
{
    family.familyId,
    name = member?.name,
}


分组操作符GroupBy根据指定的键对集合中的元素进行分组

串联操作符Concat将两个集合连接成一个新集合

聚合操作符

AggregateAverage、Count、LongCount、Max、Min、Sum

Aggregate 可以用于在集合上执行自定义的累积函数,其他方法用于计算集合中的元素的平均值、总数、最大值、最小值和总和

集合操作符

DistinctUnion、Intersect、Except

用于执行集合间的不同操作,Distinct 移除重复元素,Union 计算两个集合的并集,Intersect 计算两个集合的交集,Except 计算一个集合相对于另一个集合的差集

生成操作符

EmptyRange、Repeat

Empty 创建一个空集合,Range 创建一个包含一系列连续数字的集合,Repeat 创建一个重复多次相同元素的集合

转换操作符

AsEnumerableCast、OfType、ToArray、ToDictionary、ToList、ToLookup

这些方法用于将集合转换为不同类型的集合或字典

元素操作符

DefaultIfEmptyElementAtElementAtOrDefaultFirst、Last、FirstOrDefault、LastOrDefault、Single、SingleOrDefault

这些方法用于获取集合中的元素,处理可能的空集合或超出索引的情况

相等操作符SequenceEqual用于比较两个集合是否包含相同的元素,顺序也需要相同

量词操作符All、Any、Contains用于检查集合中的元素是否满足特定条件,All 检查是否所有元素都满足条件,Any 检查是否有任何元素满足条件,Contains 检查集合是否包含特定元素

分割操作符Skip、SkipWhile、Take、TakeWhile用于从集合中跳过一些元素或只取一部分元素,可以结合特定条件进行操作

了解立即执行延迟执行可以大大改善性能。

xoyozo 2 年前
2,152

SelectMany() 的作用与 GroupBy() 相反,例:

List<List<int>> list = new() { new() { 1, 2, 3 }, new() { 4, 5, 6 } };
return Json(list.SelectMany(c => c));

输出:

[1,2,3,4,5,6]


xoyozo 4 年前
1,816

严重性代码说明项目文件禁止显示状态

错误CS0121以下方法或属性之间的调用具有二义性:“System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource, bool>>)”和“System.Linq.AsyncEnumerable.Where<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>)”活动


The call is ambiguous between the following methods or properties.

引用的扩展或其版本有冲突,暂时在查找的表后面加上“AsQueryable()”解决。

xoyozo 5 年前
8,778

The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

在 EF 查询数据库时发生:

var list = db.TableA.Select(a => new
           {
               a.Id,
               bSum = a.TableB.Sum(b => b.Num),
           }).ToList();

本例中 TableB 有外键关联到 TableA.Id,TableB.Num 为 int,而非 int?。

原因是 EF 以为 Sum 的结果可能为 Nullable<int>,将代码修改如下即可正常:

var list = db.TableA.Select(a => new
           {
               a.Id,
               bSum = (int?)a.TableB.Sum(b => b.Num) ?? 0,
           }).ToList();


xoyozo 5 年前
3,371

ASP.NET MVC 使用 Authorize 过滤器验证用户登录。Authorize 过滤器首先运行在任何其它过滤器或动作方法之前,主要用来做登录验证或者权限验证。

示例:使用 Authorize 过滤器实现简单的用户登录验证。

1、创建登录控制器 LoginController

/// <summary>
/// 登录控制器
/// </summary>
[AllowAnonymous]
public class LoginController : Controller
{
    /// <summary>
    /// 登录页面
    /// </summary>
    public ActionResult Index()
    {
        return View();
    }
 
    /// <summary>
    /// 登录
    /// </summary>
    [HttpPost]
    public ActionResult Login(string loginName, string loginPwd)
    {
        if (loginName == "admin" && loginPwd == "123456")
        {
            // 登录成功
            Session["LoginName"] = loginName;
            return RedirectToAction("Index", "Home");
        }
        else
        {
            // 登录失败
            return RedirectToAction("Index", "Login");
        }
    }
 
    /// <summary>
    /// 注销
    /// </summary>
    public ActionResult Logout()
    {
        Session.Abandon();
        return RedirectToAction("Index", "Login");
    }
}

注意:在登录控制器 LoginController 上添加 AllowAnonymous 特性,该特性用于标记在授权期间要跳过 AuthorizeAttribute 的控制器和操作。

2、创建登录页面

@{
    ViewBag.Title = "登录页面";
    Layout = null;
}
 
<h2>登录页面</h2>
 
<form action='@Url.Action("Login","Login")' id="form1" method="post">
    用户:<input type="text" name="loginName" /><br />
    密码:<input type="password" name="loginPwd" /><br />
    <input type="submit" value="登录">
</form>

效果图:

3、创建主页控制器 LoginController

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // 获取当前登录用户
        string loginName = Session["LoginName"].ToString();
        ViewBag.Message = "当前登录用户:" + loginName;
        return View();
    }
}

4、创建主页页面

@{
    ViewBag.Title = "Index";
    Layout = null;
}
 
<h2>Index</h2>
<h3>@ViewBag.Message</h3>
<a href="@Url.Action("Logout","Login")">注销</a>

效果图:

5、创建授权过滤器 LoginAuthorizeAttribute 类

创建 Filter 目录,在该目录下创建授权过滤器 LoginAuthorizeAttribute 类,继承 AuthorizeAttribute。

using System.Web.Mvc;
 
namespace MvcApp.Filter
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class LoginAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // 判断是否跳过授权过滤器
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
               || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }
 
            // 判断登录情况
            if (filterContext.HttpContext.Session["LoginName"] == null || filterContext.HttpContext.Session["LoginName"].ToString()=="")
            {
                //HttpContext.Current.Response.Write("认证不通过");
                //HttpContext.Current.Response.End();
 
                filterContext.Result = new RedirectResult("/Login/Index");
            }
        }
    }
}

通常 Authorize 过滤器也是在全局过滤器上面的,在 App_Start 目录下的 FilterConfig 类的 RegisterGlobalFilters 方法中添加:

using System.Web;
using System.Web.Mvc;
using MvcApp.Filter;
 
namespace MvcApp
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
 
            // 添加全局授权过滤器
            filters.Add(new LoginAuthorizeAttribute());
        }
    }
}

Global.asax 下的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
 
namespace MvcApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


xoyozo:暂时没有按区域(Area)来统一配置的方法,建议加在 Controller 上。https://stackoverflow.com/questions/2319157/how-can-we-set-authorization-for-a-whole-area-in-asp-net-mvc


p
转自 pan_junbiao 5 年前
4,821

制作类似下图中的拖拽排序功能:

image.png

1. 首先数据库该表中添加字段 sort,类型为 double(MySQL 中为 double(0, 0))。

2. 页面输出绑定数据(以 ASP.NET MVC 控制器为例):

public ActionResult EditSort()
{
    if (!zConsole.Logined) { return RedirectToAction("", "SignIn", new { redirect = Request.Url.OriginalString }); }

    db_auto2018Entities db = new db_auto2018Entities();

    return View(db.dt_dealer.Where(c => c.enabled).OrderBy(c => c.sort));
}

这里可以加条件列出,即示例中 enabled == true 的数据。

3. 前台页面引用 jQuery 和 jQuery UI。

4. 使用 <ul /> 列出数据:

<ul id="sortable" class="list-group gutter list-group-lg list-group-sp">
    @foreach (var d in Model)
    {
        <li class="list-group-item" draggable="true" data-id="@d.id">
            <span class="pull-left"><i class="fa fa-sort text-muted fa m-r-sm"></i> </span>
            <div class="clear">
                【id=@d.id】@d.name_full
            </div>
        </li>
    }
</ul>

5. 初始化 sortable,当拖拽结束时保存次序:

<script>
    var url_SaveSort = '@Url.Action("SaveSort")';
</script>
<script>
    $("#sortable").sortable({
        stop: function (event, ui) {
            // console.log('index: ' + $(ui.item).index())
            // console.log('id: ' + $(ui.item).data('id'))
            // console.log('prev_id: ' + $(ui.item).prev().data('id'))
            $.post(url_SaveSort, {
                id: $(ui.item).data('id'),
                prev_id: $(ui.item).prev().data('id')
            }, function (json) {
                if (json.result.success) {
                    // window.location.reload();
                } else {
                    toastr["error"](json.result.info);
                }
            }, 'json');
        }
    });
    $("#sortable").disableSelection();
</script>

这里回传到服务端的参数为:当前项的 id 值、拖拽后其前面一项的 prev_id 值(若移至首项则 prev_id 为 undefined)。

不使用 $(ui.item).index() 是因为,在有筛选条件的结果集中排序时,使用该索引值配合 LINQ 的 .Skip 会引起取值错误。

6. 控制器接收并保存至数据库:

[HttpPost]
public ActionResult SaveSort(int id, int? prev_id)
{
    if (!zConsole.Logined)
    {
        return Json(new { result = new { success = false, msg = "请登录后重试!" } }, JsonRequestBehavior.AllowGet);
    }

    db_auto2018Entities db = new db_auto2018Entities();

    dt_dealer d = db.dt_dealer.Find(id);

    // 拖拽后其前项 sort 值(若无则 null)(此处不需要加 enabled 等筛选条件)
    double? prev_sort = prev_id.HasValue
        ? db.dt_dealer.Where(c => c.id == prev_id).Select(c => c.sort).Single()
        : null as double?;

    // 拖拽后其后项 sort 值(若无前项则取首项作为后项)(必须强制转化为 double?,否则无后项时会返回 0,导致逻辑错误)
    double? next_sort = prev_id.HasValue
        ? db.dt_dealer.Where(c => c.sort > prev_sort && c.id != id).OrderBy(c => c.sort).Select(c => (double?)c.sort).FirstOrDefault()
        : db.dt_dealer.Where(c => c.id != id).OrderBy(c => c.sort).Select(c => (double?)c.sort).FirstOrDefault();

    if (prev_sort.HasValue && next_sort.HasValue)
    {
        d.sort = (prev_sort.Value + next_sort.Value) / 2;
    }
    if (prev_sort == null && next_sort.HasValue)
    {
        d.sort = next_sort.Value - 1;
    }
    if (prev_sort.HasValue && next_sort == null)
    {
        d.sort = prev_sort.Value + 1;
    }

    db.SaveChanges();

    return Json(new { item = new { id = d.id }, result = new { success = true } });
}

需要注意的是,当往数据库添加新项时,必须将 sort 值设置为已存在的最大 sort 值 +1 或最小 sort 值 -1。

var d = new dt_dealer
{
    name_full = "新建项",
    sort = (db.dt_dealer.Max(c => (double?)c.sort) ?? 0) + 1,
};


xoyozo 7 年前
6,966

EF 提供一个查询 SQL 日志的属性:

DbContext.Database.Log

该属性是一个委托。

最简单的用法是直接输出到控制台:

DbContext.Database.Log = Console.WriteLine;

WebFrom 中可以输出到页面:

DbContext.Database.Log = Response.Write;

该委托可以带一个参数,利用它可以输出简单格式化的日志信息:

DbContext.Database.Log = (sql) =>
{
    Console.WriteLine("查询开始");
    Console.WriteLine(sql);
    Console.WriteLine("查询结束");
};

上面是直接输出到控制台或页面,当然也可以保存到变量:

string s = "";
DbContext.Database.Log = (sql) =>
{
    s += sql;
};

当然还有更强大更广泛的使用方式,有兴趣可以参阅 Jeffcky 的文章

xoyozo 8 年前
8,627

如果在 Visual Studio 2017 中打开 LINQ To SQL  的 .dbml 文件时是以 XML 的方式打开的,那么需要安装“LINQ to SQL tools”,步骤如下:

1,关闭 VS

2,运行 VS 安装程序

3,修改

      image.png

4,切换到“单个组件”选项卡,勾选“LING to SQL 工具”

      image.png

5,确认修改

xoyozo 8 年前
11,422
Dictionary<TKey, TValue> dic = q.ToDictionary(k => k.field1, v => v.field2);
xoyozo 9 年前
5,617