本文整理汇总了C#中Repository.Insert方法的典型用法代码示例。如果您正苦于以下问题:C# Repository.Insert方法的具体用法?C# Repository.Insert怎么用?C# Repository.Insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Repository
的用法示例。
在下文中一共展示了Repository.Insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: insereMunicipios
private static void insereMunicipios()
{
var repMun = new Repository<Municipio>();
var mun = new Municipio
{
Nome = "São Paulo",
UnidadeFederacaoID = 35
};
repMun.Insert(mun);
mun = new Municipio
{
Nome = "Florianópolis",
UnidadeFederacaoID = 42
};
repMun.Insert(mun);
mun = new Municipio
{
Nome = "Brasília",
UnidadeFederacaoID = 53
};
repMun.Insert(mun);
}
示例2: Here
public ActionResult Here(int locationId)
{
// Get the data
IRepository repository = new Repository(new CheckInDatabaseContext());
var location = repository.GetById<Location>(locationId);
if (location == null)
{
return new HttpNotFoundResult();
}
var username = HttpContext.User.Identity.Name;
var user = repository.Query<ApplicationUser>().SingleOrDefault(u => u.UserName == username);
if (user == null)
{
return new HttpNotFoundResult();
}
// make a new check in
var checkIn = new CheckIn();
checkIn.User = user;
checkIn.Location = location;
checkIn.Time = DateTime.Now;
repository.Insert(checkIn);
// check to see if this user meets any achievements
var allCheckins = repository.Query<CheckIn>().Where(c => c.User.Id == user.Id);
var allAchievements = repository.Query<Achievement>();
var allLocationIds = repository.Query<Location>().Select(l => l.Id);
// two in one day?
if (!allAchievements.Any(a => a.Type == AchievementType.TwoInOneDay) && allCheckins.Count(c => EntityFunctions.TruncateTime(c.Time) == DateTime.Today) > 2)
{
var twoInOneDay = new Achievement { Type = AchievementType.TwoInOneDay, User = user, TimeAwarded = DateTime.Now };
repository.Insert(twoInOneDay);
}
// all locations?
var hasAll = false;
foreach (var testLocationId in allLocationIds)
{
hasAll = hasAll || allCheckins.Any(c => c.Location.Id == testLocationId);
}
if (!allAchievements.Any(a => a.Type == AchievementType.AllLocations) && hasAll)
{
var allLocations = new Achievement { Type = AchievementType.AllLocations, User = user, TimeAwarded = DateTime.Now };
repository.Insert(allLocations);
}
// some day we'll have hundreds of achievements!
repository.SaveChanges();
return RedirectToAction("Index");
}
示例3: BasicCrud
public void BasicCrud()
{
using (var trans = DataSource.BeginTransaction())
{
var repo = new Repository<Employee, int>(trans, EmployeeTableName);
var emp1 = new Employee() { FirstName = "Tom", LastName = "Jones", Title = "President" };
var echo1 = repo.Insert(emp1);
Assert.AreNotEqual(0, echo1.EmployeeKey, "EmployeeKey was not set");
Assert.AreEqual(emp1.FirstName, echo1.FirstName, "FirstName");
Assert.AreEqual(emp1.LastName, echo1.LastName, "LastName");
Assert.AreEqual(emp1.Title, echo1.Title, "Title");
echo1.MiddleName = "G";
repo.Update(echo1);
var emp2 = new Employee() { FirstName = "Lisa", LastName = "Green", Title = "VP Transportation", ManagerKey = echo1.EmployeeKey };
var echo2 = repo.Insert(emp2);
Assert.AreNotEqual(0, echo2.EmployeeKey, "EmployeeKey was not set");
Assert.AreEqual(emp2.FirstName, echo2.FirstName, "FirstName");
Assert.AreEqual(emp2.LastName, echo2.LastName, "LastName");
Assert.AreEqual(emp2.Title, echo2.Title, "Title");
Assert.AreEqual(emp2.ManagerKey, echo2.ManagerKey, "ManagerKey");
var list = repo.GetAll();
Assert.IsTrue(list.Any(e => e.EmployeeKey == echo1.EmployeeKey), "Employee 1 is missing");
Assert.IsTrue(list.Any(e => e.EmployeeKey == echo2.EmployeeKey), "Employee 2 is missing");
var get1 = repo.Get(echo1.EmployeeKey.Value);
Assert.AreEqual(echo1.EmployeeKey, get1.EmployeeKey);
var whereSearch1 = repo.Query("FirstName = @FN", new { FN = "Tom" });
Assert.IsTrue(whereSearch1.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
Assert.IsTrue(whereSearch1.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");
var whereSearch2 = repo.Query(new { FirstName = "Tom" });
Assert.IsTrue(whereSearch2.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
Assert.IsTrue(whereSearch2.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");
repo.Delete(echo2.EmployeeKey.Value);
repo.Delete(echo1.EmployeeKey.Value);
var list2 = repo.GetAll();
Assert.AreEqual(list.Count - 2, list2.Count);
trans.Commit();
}
}
示例4: Should_insert_new_record_and_populate_Id
public void Should_insert_new_record_and_populate_Id()
{
var orderDate = DateTime.Now.AddDays(-20);
var requiredDate = DateTime.Now.AddDays(-10);
var shippedDate = DateTime.Now.AddDays(-15);
var newOrder = new Order
{
CustomerID = "ABCDE",
EmployeeID = 5,
Freight = 12.13m,
OrderDate = orderDate,
RequiredDate = requiredDate,
ShipName = "My Stuff",
ShipAddress = "P.O. Box 123",
ShipCity = "London",
ShipPostalCode = "EC1 4RT",
ShipCountry = "UK",
ShipVia = 3,
ShippedDate = shippedDate
};
using (var context = new RepositoryTest())
{
var repo = new Repository<Order>(context);
repo.Insert(newOrder);
}
Assert.AreEqual(10348, newOrder.OrderID);
}
示例5: Child_Insert
private void Child_Insert(Repository repository, int companyID)
{
LoadProperty(CompanyIDProperty, companyID);
var dto = ToDTO();
repository.Insert(dto);
LoadProperty(EmployeeStatusIDProperty, dto.EmployeeStatusID);
}
示例6: RegistrarUsuario
public static object RegistrarUsuario(string usuarioJSON)
{
using (var dataContext = new OBJ_REDDataContext())
{
var usuRepo = new Repository<Usuario>(dataContext);
Usuario usuario = JsonConvert.DeserializeObject<Usuario>(usuarioJSON);
usuario.Password = GenerarPassword();
try
{
usuRepo.Insert(usuario);
dataContext.SubmitChanges();
Correo.EnviarCorreo(Tipo.NuevoUsuario, usuario);
return (new
{
valido = true,
mensaje = "Usuario correctamente registrado. La contraseña fue enviada a tu correo."
});
}
catch (Exception)
{
return (new
{
valido = false,
mensaje = "Hubo un error al intentar registrar tu usuario."
});
}
}
}
示例7: Start
public void Start()
{
var url = "http://www.translationdirectory.com/translation_jobs.php";
Console.WriteLine("Url: " + url);
var web = new HtmlWeb();
var languageList = new List<LanguageModel>();
var languagePairJobList = new List<LanguagePairJobModel>();
try
{
var doc = web.Load(url);
var nodes = doc.DocumentNode.SelectNodes(".//div").Where(k => k.Attributes.Contains("class") && k.Attributes["class"].Value.Contains("box_informer"));
var stt = 0;
foreach (var node in nodes)
{
var childNodes = node.SelectNodes(".//tr");
foreach (var childNode in childNodes)
{
var language = new LanguageModel();
var languagePairJob = new LanguagePairJobModel();
var datahtml = childNode.SelectSingleNode(".//strong").InnerText;
if (datahtml.Contains("to"))
{
var checkLanguage = datahtml.Split(new string[] { "to" }, StringSplitOptions.None)[0].Trim();
if (languageList.Count(x => x.Name.Contains(checkLanguage)) == 0)
{
language.Name = checkLanguage;
languageList.Add(language);
}
var checkTarget = datahtml.Split(new string[] {"to"}, StringSplitOptions.None)[1];
if (languagePairJobList.Count(x => x.Source.Contains(checkLanguage) && x.Target.Contains(checkTarget)) == 0)
{
languagePairJob.Source = checkLanguage;
languagePairJob.Target = checkTarget.Split(new string[] { "Translation" }, StringSplitOptions.None)[0].Trim();
languagePairJobList.Add(languagePairJob);
}
}
}
}
Console.WriteLine("BEGIN INSERT INTO Language...");
foreach (var item in languageList)
{
var repoLanguage = new Repository<LanguageModel>("Language");
repoLanguage.Insert(item);
}
Console.WriteLine("BEGIN INSERT INTO LanguagePairJob...");
foreach (var item in languagePairJobList)
{
var repoLanguagePairJob = new Repository<LanguagePairJobModel>("LanguagePairJob");
repoLanguagePairJob.Insert(item);
}
Console.WriteLine("DONE!!!!");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
示例8: InitializeDatabase
public void InitializeDatabase()
{
var hmacSettings = IntegrationTestHelper.ReadHmacSettings();
IntegrationTestInitializer.DatabaseCallback = conn =>
{
conn.CreateTableIfNotExists<AppMember>();
conn.CreateTableIfNotExists<IdentityUserClaim>();
conn.CreateTableIfNotExists<IdentityUserLogin>();
conn.CreateTableIfNotExists<IdentityUserService>();
};
IntegrationTestInitializer.TestDataCallback = (sid, uid, aid, dbn, sec) =>
{
var userRepository = new Repository<AppMember>();
var email = Guid.NewGuid().ToString() + "@test.local";
userRepository.Insert(new AppMember { Id = hmacSettings.UserId, UserName = email, Email = email});
var loginRepository = new Repository<IdentityUserLogin>();
loginRepository.Insert(new IdentityUserLogin
{
LoginProvider = LoginProvider,
ProviderKey = Guid.NewGuid().ToString(),
UserId = hmacSettings.UserId
});
};
IntegrationTestInitializer.CreateTestDatabase(new Guid(hmacSettings.ServiceId), new Guid(hmacSettings.UserId), new Guid(hmacSettings.AppId), TestDbName, hmacSettings.Secret, TargetDbPath);
}
示例9: InsertTestData
private static void InsertTestData(Guid serviceId, Guid userId, Guid appId, string dbName, string secret)
{
var hmacUserRepository = new Repository<UserModel>();
hmacUserRepository.Insert(new UserModel { Id = 1, ServiceId = serviceId, UserId = userId, AppId = appId, Enabled = true, CreatedAt = DateTime.UtcNow });
var hmacAppRepository = new Repository<AppModel>();
hmacAppRepository.Insert(new AppModel { Id = 1, ServiceId = serviceId, AppId = appId, CreatedAt = DateTime.UtcNow, Enabled = true, Name = dbName, Secret = secret });
}
示例10: Join_example_with_transaction_insert
public void Join_example_with_transaction_insert()
{
Repository.DefaultConnectionString = @"Data source=.\SQLEXPRESS;Initial Catalog=WeenyMapper;Trusted_Connection=true";
Repository.DefaultConvention = new BlogConvention();
var myBlog = new Blog("My blog");
var steve = new User("Steve", "password");
var post1 = new BlogPost("Title 1", "Content 1 goes here") { Blog = myBlog, Author = steve };
var post2 = new BlogPost("Title 2", "Content 2 goes here") { Blog = myBlog, Author = steve };
var post3 = new BlogPost("Title 3", "Content 3 goes here") { Blog = myBlog, Author = steve };
var post4 = new BlogPost("Title 4", "Content 4 goes here") { Blog = myBlog, Author = steve };
using (var repository = new Repository())
{
using (var transaction = repository.BeginTransaction())
{
repository.Insert(myBlog);
repository.Insert(steve);
repository.Insert(post1, post2, post3, post4);
transaction.Commit();
}
repository.Update<BlogPost>()
.Set(x => x.Title, "Updated title 2")
.Where(x => x.Id == post2.Id)
.Execute();
repository.Delete<BlogPost>()
.Where(x => x.Id == post3.Id || x.Title == "Title 4")
.Execute();
var actualBlog = repository.Find<Blog>().Where(x => x.Id == myBlog.Id)
.Join(x => x.Posts, x => x.Blog)
.OrderBy<BlogPost>(x => x.Title)
.Execute();
Assert.AreEqual("My blog", actualBlog.Name);
Assert.AreEqual(2, actualBlog.Posts.Count);
Assert.AreEqual("Title 1", actualBlog.Posts[0].Title);
Assert.AreEqual("Updated title 2", actualBlog.Posts[1].Title);
}
}
示例11: Main
static void Main(string[] args)
{
using (var context = new GamesStoreContext())
{
var parser = new GameParser();
var repo = new Repository<GameDTO>(context);
for (int i = 1; i <= 8; i++)
{
using (var errorLog = new StreamWriter($"..\\..\\puzzles\\errorLog.txt"))
using (var reader = new StreamReader($"..\\..\\puzzles\\m2_{i}.pgn"))
{
var builder = new StringBuilder();
var line = string.Empty;
while (!reader.EndOfStream)
{
builder.Clear();
builder.AppendLine(line);
while (!reader.EndOfStream && !(line = reader.ReadLine()).Contains("Event"))
{
if (line.Contains("Date"))
{
line = line.Replace("-", ".");
line.Replace("\"?\"", "\"????\"");
}
// Skip [Round] as it's not properly parsed by pgn
if (line.Contains("Round")) continue;
builder.AppendLine(line);
}
var text = builder.ToString();
text = text.TrimEnd('\r', '\n');
try
{
foreach (var game in parser.Parse(text))
{
var gameDto = new GameDTO()
{
PgnString = text
};
repo.Insert(gameDto);
repo.Save();
}
}
catch (Exception ex)
{
errorLog.WriteLine($"File m2_{i}.pgn\n Error: {ex.Message}\n While parsing FEN: {text}");
}
}
}
Console.WriteLine($"File m2_{i}.pgn processed");
}
}
}
示例12: Execute
public void Execute(object state)
{
var logInfo = new LogInfo
{
MethodInstance = MethodBase.GetCurrentMethod(),
ThreadInstance = Thread.CurrentThread
};
try
{
_log.Info("Scheduler Start: (AutoUpdateMonthlyRank)", logInfo);
IRepository repo = new Repository();
var iDay = DateTime.Today;
var firstBetDate = repo.Single<Bet>(1).BetTime;
while (!(iDay.Year <= firstBetDate.Year && iDay.Month < firstBetDate.Month))
{
var winner = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Winner);
var loser = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Loser);
var rper = GamblerDW.GetTopGamblerMonthly(iDay, RankType.RP);
if (winner != null && loser != null)
{
var day = iDay;
var rank = repo.Query<Rank>(x => x.RankYear == day.Year && x.RankMonth == day.Month).FirstOrDefault();
if (rank != null)
{
//update
rank.Init(winner, loser, rper);
repo.Update(rank);
}
else
{
//insert
var instance = new Rank { RankYear = day.Year, RankMonth = day.Month };
instance.Init(winner, loser, rper);
repo.Insert(instance);
}
}
iDay = iDay.AddMonths(-1);
}
_log.Info("Scheduler End: (AutoUpdateMonthlyRank)", logInfo);
}
catch (Exception ex)
{
_log.Warn(ex, logInfo);
}
}
示例13: AddCountryHelper
public static bool AddCountryHelper(CountryModel model)
{
var repo = new Repository<CountryModel>(DbCollection.Country);
if (repo.Gets().Any(m => m.Name.Equals(model.Name)))
{
return false;
}
repo.Insert(model);
return true;
}
示例14: ShouldInsert
public void ShouldInsert()
{
// arrange
Repository<string> r = new Repository<string>(m_session.Object);
string s = "this";
// act
r.Insert(s);
// assert
m_session.Verify(x => x.Save((object)s));
}
示例15: InsertProducts
public void InsertProducts()
{
using (IDataContextAsync context = new NorthwindContext())
using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
{
IRepositoryAsync<Product> productRepository = new Repository<Product>(context, unitOfWork);
var newProducts = new[]
{
new Product {ProductName = "One", Discontinued = false, ObjectState = ObjectState.Added},
new Product {ProductName = "12345678901234567890123456789012345678901234567890", Discontinued = true, ObjectState = ObjectState.Added},
new Product {ProductName = "Three", Discontinued = true, ObjectState = ObjectState.Added},
new Product {ProductName = "Four", Discontinued = true, ObjectState = ObjectState.Added},
new Product {ProductName = "Five", Discontinued = true, ObjectState = ObjectState.Added}
};
foreach (var product in newProducts)
{
try
{
productRepository.Insert(product);
unitOfWork.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
Debug.WriteLine(sb.ToString());
TestContext.WriteLine(sb.ToString());
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
TestContext.WriteLine(ex.Message);
}
}
var insertedProduct = productRepository.Query(x => x.ProductName == "One").Select().FirstOrDefault();
Assert.IsTrue(insertedProduct.ProductName == "One");
}
}