本文整理汇总了C#中DataContext类的典型用法代码示例。如果您正苦于以下问题:C# DataContext类的具体用法?C# DataContext怎么用?C# DataContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DataContext类属于命名空间,在下文中一共展示了DataContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetupAsync
public async Task SetupAsync()
{
_evnt = new EventViewModel
{
Title = "Title event",
Description = "Test event",
Start = "11:00",
End = "14:27",
Date = "2016-02-01"
};
var userViewModel = new LoginViewModel
{
Email = "[email protected]",
Password = "useruser",
RememberMe = false
};
var context = new DataContext();
var manager = new UserManager(new UserStore(context));
var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
if (user == null)
{
await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
}
_calendarController = new CalendarController(context);
var mockCp = new Mock<IClaimsPrincipal>();
if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
_calendarController.CurrentUser = mockCp.Object;
var mockAuthenticationManager = new Mock<IAuthenticationManager>();
mockAuthenticationManager.Setup(am => am.SignOut());
mockAuthenticationManager.Setup(am => am.SignIn());
_calendarController.AuthenticationManager = mockAuthenticationManager.Object;
}
示例2: Main
static void Main(string[] args)
{
DataContext dc = new DataContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True");
dc.Log = Console.Out;
//Table<Pessoa> pessoas = dc.GetTable<Pessoa>();
var pessoas = from p in dc.GetTable<Pessoa>()
select p;
//ObjectDumper.Write(pessoas);
//Console.WriteLine();
var nomes = from p in pessoas
select p.Nome;
nomes = from p in nomes
where p.Equals("ABEL")
select p;
ObjectDumper.Write(nomes);
Console.ReadKey();
}
示例3: RepositoryBase
/// <summary>
/// Constructor initializes DataContext
/// plus adds additional configuration
/// </summary>
public RepositoryBase()
{
dc = new DataContext();
dc.Configuration.LazyLoadingEnabled = false;
dc.Configuration.ProxyCreationEnabled = false;
}
示例4: Login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
using (var db = new DataContext())
{
ViewBag.LoginsList = db.Users.ToArray();
}
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
示例5: AddOrUpdate
private void AddOrUpdate(List<ExcelDeltaker> deltakere, DataContext context)
{
var alleLag = context.Lag.ToList();
foreach (var excelDeltaker in deltakere)
{
var deltaker = context.Deltakere.SingleOrDefault(x => x.Kode == excelDeltaker.Kode);
var lag = alleLag.SingleOrDefault(x => x.LagId == excelDeltaker.LagId);
if (deltaker == null)
{
context.Deltakere.Add(new Deltaker
{
DeltakerId = Guid.NewGuid().ToString(),
Navn = excelDeltaker.Navn,
Kode = excelDeltaker.Kode,
Lag = lag
});
}
else
{
deltaker.Navn = excelDeltaker.Navn;
deltaker.Lag = lag;
}
}
}
示例6: CreateDBLinqDataContext
//private static TextWriter dbLinqLogWriter = new StreamWriter(@"C:\Temp\sipsorcery\dblinq.log", true, Encoding.ASCII);
public static DataContext CreateDBLinqDataContext(StorageTypes storageType, string connectionString) {
DataContext dataContext = null;
//DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
//new MySql.Data.MySqlClient.MySqlClientFactory();
//DbProviderFactory factory = Npgsql.NpgsqlFactory.Instance;
switch (storageType) {
case StorageTypes.DBLinqMySQL:
IDbConnection mySqlConn = new MySqlConnection(connectionString);
dataContext = new DataContext(mySqlConn, m_mappingSource, new DbLinq.MySql.MySqlVendor());
break;
case StorageTypes.DBLinqPostgresql:
IDbConnection npgsqlConn = new NpgsqlConnection(connectionString);
dataContext = new DataContext(npgsqlConn, m_mappingSource, new DbLinq.PostgreSql.PgsqlVendor());
break;
default:
throw new NotSupportedException("Database type " + storageType + " is not supported by CreateDBLinqDataContext.");
}
//dataContext.QueryCacheEnabled = true;
//dataContext.Log = Console.Out;
//dataContext.Log = dbLinqLogWriter;
dataContext.ObjectTrackingEnabled = false;
return dataContext;
}
示例7: EventCategorySingleViewModel
public EventCategorySingleViewModel(string category, HttpServerUtilityBase server)
{
_server = server;
category = formatCategoryString(category);
//ImageList = getImageList();
using (var context = new DataContext())
{
var tomorrow = DateTime.Now.Date;
TheCategory = context.EventCategories.FirstOrDefault(x => x.CategoryName == category);
EventRoll = context.Events.Where(x => x.MainCategory == category && x.IsActive == true && DateTime.Compare(x.EndDate.Value, tomorrow) >= 0).ToList();
// Set a random picture on the eventRoll if none is currently set
//foreach (var event in EventRoll)
//{
// if (String.IsNullOrEmpty(event.ImageUrl))
// {
// event.ImageUrl = getRandomImage();
// }
//}
}
}
示例8: SiteTreeEditModel
/// <summary>
/// Creates a new site tree model for the given namespace.
/// </summary>
/// <param name="id">Namespace id</param>
public SiteTreeEditModel(Guid namespaceId)
{
// Get the namespaces
using (var db = new DataContext()) {
var ns = db.Namespaces.OrderBy(n => n.Name).ToList() ;
if (namespaceId != Guid.Empty)
Namespaces = new SelectList(ns, "Id", "Name", namespaceId) ;
Namespaces = new SelectList(ns, "Id", "Name") ;
}
// Get the available region types
RegionTypes = new List<dynamic>() ;
ExtensionManager.Extensions.Where(e => e.ExtensionType == ExtensionType.Region).OrderBy(e => e.Name).Each((i, r) =>
RegionTypes.Add(new { Name = r.Name, Type = r.Type.ToString() })) ;
RegionTypes.Insert(0, new { Name = "", Type = "" }) ;
// Initialize the new site
Id = Guid.NewGuid() ;
NamespaceId = namespaceId ;
Template = new PageTemplate() {
Id = Id,
Name = Id.ToString(),
IsSiteTemplate = true
} ;
Regions = Template.RegionTemplates ;
}
示例9: TestContext
public void TestContext(string context)
{
var ctx = new DataContext(context);
ctx.GetTable<Person>().ToList();
ctx.KeepConnectionAlive = true;
ctx.GetTable<Person>().ToList();
ctx.GetTable<Person>().ToList();
ctx.KeepConnectionAlive = false;
using (var tran = new DataContextTransaction(ctx))
{
ctx.GetTable<Person>().ToList();
tran.BeginTransaction();
ctx.GetTable<Person>().ToList();
ctx.GetTable<Person>().ToList();
tran.CommitTransaction();
}
}
示例10: CMetaobjectExtented
public CMetaobjectExtented(Guid ID, DataContext Context)
: base(ID, Context)
{
this._likesNumberAttribute.Attributes = this._attributes;
this.LikesNumber = 0;
}
示例11: AmountInsert
public int AmountInsert(DataContext Context)
{
var Amounts = Context.GetTable<CMenuServiceOrderAmount>();
Amounts.InsertOnSubmit(this);
return CErrors.ERR_SUC;
}
示例12: Test2
public void Test2()
{
var dc = new DataContext();
dc.AddTable("data", new[] {
new Item { Col1="A", Col2 = 2 }
});
var flow = new Flow { Orientation = FlowOrientation.Vertical };
var table = flow.AddTable<Item>("data");
table.Columns.Single(a => a.DataField == "Col2").ConditionalFormatting = (value) => {
if (!(value is int))
return null;
var v = (int)value;
if (v > 0)
return new Styling.CellStyle
{
FontStyle = new Styling.FontStyle
{
FontColor = Styling.Color.FromHtml("#00FF00")
}
};
return null;
};
var rep = Report.CreateReport(flow, dc);
var cells = ReportUtil.GetCellMatrix(rep);
Assert.IsNull(cells[0][0].CustomStyle);
Assert.IsNotNull(cells[0][1].CustomStyle);
var html = HtmlReportWriter.RenderReport(rep, new DefaultHtmlReportTheme());
Assert.IsTrue(html.Contains("style=\"color:"));
Assert.IsTrue(html.Contains("#00FF00"));
}
示例13: BlogsByUserViewModel
public BlogsByUserViewModel(string username)
{
// Get back to the original name before url conversion
BlogUsername = username.Replace(ContentGlobals.BLOGDELIMMETER, " ");
using (var context = new DataContext())
{
// Get User based on authorid
TheBlogUser = context.BlogUsers.FirstOrDefault(x => x.Username == BlogUsername);
MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;
BlogTitle = BlogListModel.GetBlogSettings().BlogTitle;
BlogsByUser = context.Blogs.Where(x => x.Author == BlogUsername && x.IsActive)
.OrderByDescending(blog => blog.Date)
.Take(MaxBlogCount)
.ToList();
// Try permalink first
TheBlog = BlogsByUser.FirstOrDefault(x => x.Author == BlogUsername);
if (BlogsByUser.Count > 0)
{
LastBlogId = BlogsByUser.LastOrDefault().BlogId;
}
}
}
示例14: LinkInsert
public int LinkInsert(DataContext Context)
{
var Links = Context.GetTable<CRdsAttributeLink>();
Links.InsertOnSubmit(this);
return -1;
}
示例15: buscarporId
//cambBuscar
//*creavuelo
public Vuelo buscarporId(int idVuelo)
{
Vuelo vuelo = new Vuelo();
MyConnection myConnection = new MyConnection();
DataContext datacontext = new DataContext(myConnection.SQLConnection);
var Table = datacontext.GetTable<Vuelo>();
try
{
var buscarPorIdVuelo = from vueloId in Table
where vueloId.IdVuelo == idVuelo
select vueloId;
foreach (Vuelo v in buscarPorIdVuelo)
{
vuelo = v;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return vuelo;
}