我想知道是否有人可以帮助我在现有数据库上创建datacontext并从中进行搜索。
到目前为止我做了什么:
这是我用过的代码。
DataContext类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace KendoUIMvcCim.Models
{
public class CustDataContext : DbContext
{
public DbSet<Contacts> CLIENT { get; set; }
}
}
我要搜索的信息的模型类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace KendoUIMvcCim.Models
{
public class Contacts
{
[Key]
public int CLIENT_ID { get; set; }
public string FIRSTNAME { get; set; }
public string LASTNAME { get; set; }
public string TEL_TEL1 { get; set; }
public string TEL_TEL2 { get; set; }
public string TEL_GSM { get; set; }
}
}
控制器
public ActionResult Testi(int? clientid)
{
using (var db = new CustDataContext())
{
var contact = db.CLIENT.Find(clientid);
if (contact != null)
{
return View(contact);
}
else
{
return RedirectToAction("Index", "Customer");
}
}
任何帮助将不胜感激!
祝你好运, 埃罗
答案 0 :(得分:0)
像这样使用Linq:
public ActionResult Index(string searchTerm = null)
{
var model =
_db.Clients
.Where(r => searchTerm == null || r.FirstName.StartsWith(searchTerm) || r.LastName.StartsWith(searchTerm))
.Take(10)
.Select r;
return View(model);
}
索引视图可能是这样的:
@model IEnumerable<AppName.Models.ModelName>
@{
ViewBag.Title = "Home Page";
}
<form method="GET">
<input type="search" name="searchTerm" />
<input type="submit" value="Search for a name"/>
</form>
@try
{
foreach (var item in Model)
{
<h3>@Html.DisplayFor(modelItem => item.FirstName)</h3>
<p>@Html.DisplayFor(modelItem => item.LastName)</p>
}
}
catch (NullReferenceException nullex)
{
<p>@nullex</p>
}
答案 1 :(得分:0)
一种搜索“类型列表”中任何属性的通用方法
public static IEnumerable<T> SearchColumns<T>(this IEnumerable<T> obj, string searchkey)
{
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);
if (properties == null)
throw new ArgumentException("{typeof(T).Name}' does not implement a public get property named '{key}.");
var filteredObj = obj.Where(d => properties.Any(p => p.GetValue(d).ToString().Contains(searchkey))).ToList();
return filteredObj;
}