本文整理汇总了C#中DbContext.Add方法的典型用法代码示例。如果您正苦于以下问题:C# DbContext.Add方法的具体用法?C# DbContext.Add怎么用?C# DbContext.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DbContext
的用法示例。
在下文中一共展示了DbContext.Add方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public static void Run(DbContext db)
{
if (!db.Set<Profile>().Any())
db.Add(new Profile
{
Name = "Alexandre Machado",
Email = "[email protected]",
Login = "cwinet\alexandrelima"
});
if (!db.Set<Skill>().Any())
db.AddRange(
new Skill { SkillName = "ASP.NET" },
new Skill { SkillName = "Ruby" },
new Skill { SkillName = "JavaScript" }
);
if (!db.Set<Mastery>().Any())
db.AddRange(
new Mastery { Code = 10, Name = "Iniciante", Description = "recordação não-situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
new Mastery { Code = 20, Name = "Competente", Description = "recordação situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
new Mastery { Code = 30, Name = "Proeficiente", Description = "recordação situacional, reconhecimento holítico, decisão analítica, consciência monitorada" },
new Mastery { Code = 40, Name = "Experiente", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência monitorada" },
new Mastery { Code = 50, Name = "Mestre", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência absorvida" });
db.SaveChanges();
}
示例2: PopulateData
private static void PopulateData(DbContext context, DateTime latestAlbumDate)
{
var albums = TestAlbumDataProvider.GetAlbums(latestAlbumDate);
foreach (var album in albums)
{
context.Add(album);
}
context.SaveChanges();
}
示例3: It_throws_object_disposed_exception
public async void It_throws_object_disposed_exception()
{
var context = new DbContext(new DbContextOptions<DbContext>());
context.Dispose();
// methods (tests all paths)
Assert.Throws<ObjectDisposedException>(() => context.Add(new object()));
Assert.Throws<ObjectDisposedException>(() => context.Attach(new object()));
Assert.Throws<ObjectDisposedException>(() => context.Update(new object()));
Assert.Throws<ObjectDisposedException>(() => context.Remove(new object()));
Assert.Throws<ObjectDisposedException>(() => context.SaveChanges());
await Assert.ThrowsAsync<ObjectDisposedException>(() => context.SaveChangesAsync());
var methodCount = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Count();
var expectedMethodCount = 27;
Assert.True(
methodCount == expectedMethodCount,
userMessage: $"Expected {expectedMethodCount} methods on DbContext but found {methodCount}. " +
"Update test to ensure all methods throw ObjectDisposedException after dispose.");
// getters
Assert.Throws<ObjectDisposedException>(() => context.ChangeTracker);
Assert.Throws<ObjectDisposedException>(() => context.Model);
var expectedProperties = new List<string> { "ChangeTracker", "Database", "Model" };
Assert.True(expectedProperties.SequenceEqual(
typeof(DbContext)
.GetProperties()
.Select(p => p.Name)
.OrderBy(s => s)
.ToList()),
userMessage: "Unexpected properties on DbContext. " +
"Update test to ensure all getters throw ObjectDisposedException after dispose.");
Assert.Throws<ObjectDisposedException>(() => ((IInfrastructure<IServiceProvider>)context).Instance);
}
示例4: PopulateDataForEventSignup
private static void PopulateDataForEventSignup(DbContext context)
{
if (!populatedData)
{
var campaignEvents = TestEventModelProvider.GetEvents();
foreach (var campaignEvent in campaignEvents)
{
context.Add(campaignEvent);
context.Add(campaignEvent.Campaign);
}
context.SaveChanges();
populatedData = true;
}
}
示例5: Navigation_fixup_happens_with_compiled_metadata_using_non_standard_collection_access
public void Navigation_fixup_happens_with_compiled_metadata_using_non_standard_collection_access()
{
var optionsBuilder = new DbContextOptionsBuilder()
.UseModel(new _OneTwoThreeContextModel());
optionsBuilder.UseInMemoryStore();
using (var context = new DbContext(optionsBuilder.Options))
{
context.Add(new KoolEntity6 { Id = 11, Kool5Id = 24 });
context.Add(new KoolEntity5 { Id = 21 });
context.Add(new KoolEntity6 { Id = 12, Kool5Id = 24 });
context.Add(new KoolEntity5 { Id = 22 });
context.Add(new KoolEntity5 { Id = 23 });
context.Add(new KoolEntity6 { Id = 13, Kool5Id = 25 });
context.Add(new KoolEntity5 { Id = 24 });
context.Add(new KoolEntity5 { Id = 25 });
Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity6>().Count());
Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity5>().Count());
foreach (var entry in context.ChangeTracker.Entries<KoolEntity6>())
{
var entity = entry.Entity;
Assert.Equal(entity.Kool5Id, entity.Kool5.Id);
Assert.Contains(entity, entity.Kool5.Kool6s);
}
}
}
示例6: FixupTest
private static void FixupTest(IModel model)
{
var optionsBuilder = new DbContextOptionsBuilder()
.UseModel(model);
optionsBuilder.UseInMemoryStore(persist: false);
using (var context = new DbContext(optionsBuilder.Options))
{
var guid1 = Guid.NewGuid();
var guid2 = Guid.NewGuid();
var guid3 = Guid.NewGuid();
context.Add(new KoolEntity1 { Id1 = 11, Id2 = guid1, KoolEntity2Id = 24 });
context.Add(new KoolEntity1 { Id1 = 12, Id2 = guid2, KoolEntity2Id = 24 });
context.Add(new KoolEntity1 { Id1 = 13, Id2 = guid3, KoolEntity2Id = 25 });
context.Add(new KoolEntity2 { Id = 21, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 });
context.Add(new KoolEntity2 { Id = 22, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 });
context.Add(new KoolEntity2 { Id = 23, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 35 });
context.Add(new KoolEntity2 { Id = 24, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 });
context.Add(new KoolEntity2 { Id = 25, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 });
context.Add(new KoolEntity3 { Id = 31 });
context.Add(new KoolEntity3 { Id = 32 });
context.Add(new KoolEntity3 { Id = 33 });
context.Add(new KoolEntity3 { Id = 34 });
context.Add(new KoolEntity3 { Id = 35 });
Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity1>().Count());
Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity2>().Count());
Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity3>().Count());
foreach (var entry in context.ChangeTracker.Entries<KoolEntity1>())
{
var entity = entry.Entity;
Assert.Equal(entity.KoolEntity2Id, entity.NavTo2.Id);
Assert.Contains(entity, entity.NavTo2.NavTo1s);
}
foreach (var entry in context.ChangeTracker.Entries<KoolEntity2>())
{
var entity = entry.Entity;
// TODO: This broke after removing IForeignKey.ReferencingProperties
//Assert.Equal(entity.KoolEntity1Id1, entity.NavTo1.Id1);
//Assert.Equal(entity.KoolEntity1Id2, entity.NavTo1.Id2);
//Assert.Contains(entity, entity.NavTo1.NavTo2s);
}
}
}
示例7: PopulateData
private void PopulateData(DbContext context)
{
if (!populatedData)
{
var activities = TestActivityModelProvider.GetActivities();
foreach (var activity in activities)
{
context.Add(activity);
context.Add(activity.Campaign);
activitiesAdded++;
}
context.SaveChanges();
populatedData = true;
}
}
示例8: Can_use_self_referencing_overlapping_FK_PK
[Fact] // Issue #3376
public virtual void Can_use_self_referencing_overlapping_FK_PK()
{
var modelBuilder = CreateModelBuilder();
modelBuilder.Entity<ModifierGroupHeader>()
.HasKey(x => new { x.GroupHeaderId, x.AccountId });
modelBuilder.Entity<ModifierGroupHeader>()
.HasOne(x => x.ModifierGroupHeader2)
.WithMany(x => x.ModifierGroupHeader1)
.HasForeignKey(x => new { x.LinkedGroupHeaderId, x.AccountId });
var contextOptions = new DbContextOptionsBuilder()
.UseModel(modelBuilder.Model)
.UseInMemoryDatabase()
.Options;
using (var context = new DbContext(contextOptions))
{
var parent = context.Add(new ModifierGroupHeader { GroupHeaderId = 77, AccountId = 90 }).Entity;
var child1 = context.Add(new ModifierGroupHeader { GroupHeaderId = 78, AccountId = 90 }).Entity;
var child2 = context.Add(new ModifierGroupHeader { GroupHeaderId = 79, AccountId = 90 }).Entity;
child1.ModifierGroupHeader2 = parent;
child2.ModifierGroupHeader2 = parent;
context.SaveChanges();
AssertGraph(parent, child1, child2);
}
using (var context = new DbContext(contextOptions))
{
var parent = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 77);
var child1 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 78);
var child2 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 79);
AssertGraph(parent, child1, child2);
}
}
示例9: Can_use_self_referencing_overlapping_FK_PK
[Fact] // Issue #3376
public virtual void Can_use_self_referencing_overlapping_FK_PK()
{
var modelBuilder = CreateModelBuilder();
modelBuilder.Entity<Node>(b =>
{
b.HasKey(e => new { e.ListId, e.PreviousNodeId });
b.HasOne(e => e.NextNode)
.WithOne(e => e.PreviousNode)
.HasForeignKey<Node>(e => new { e.ListId, e.NextNodeId });
});
var contextOptions = new DbContextOptionsBuilder()
.UseModel(modelBuilder.Model)
.UseInMemoryDatabase()
.Options;
using (var context = new DbContext(contextOptions))
{
var node1 = context.Add(new Node { ListId = 90, PreviousNodeId = 77 }).Entity;
var node2 = context.Add(new Node { ListId = 90, PreviousNodeId = 78 }).Entity;
var node3 = context.Add(new Node { ListId = 90, PreviousNodeId = 79 }).Entity;
node1.NextNode = node2;
node3.PreviousNode = node2;
context.SaveChanges();
AssertGraph(node1, node2, node3);
}
using (var context = new DbContext(contextOptions))
{
var node1 = context.Set<Node>().Single(e => e.PreviousNodeId == 77);
var node2 = context.Set<Node>().Single(e => e.PreviousNodeId == 78);
var node3 = context.Set<Node>().Single(e => e.PreviousNodeId == 79);
AssertGraph(node1, node2, node3);
}
}
示例10: Can_add_update_delete_end_to_end_using_partial_shadow_state
public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state()
{
var model = new Model();
var customerType = new EntityType(typeof(Customer));
customerType.SetKey(customerType.AddProperty("Id", typeof(int), shadowProperty: false, concurrencyToken: false));
customerType.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: false);
model.AddEntityType(customerType);
var options = new DbContextOptions()
.UseModel(model)
.UseInMemoryStore();
var customer = new Customer { Id = 42 };
using (var context = new DbContext(options))
{
context.Add(customer);
// TODO: Better API for shadow state access
var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
customerEntry[customerType.GetProperty("Name")] = "Daenerys";
await context.SaveChangesAsync();
customerEntry[customerType.GetProperty("Name")] = "Changed!";
}
using (var context = new DbContext(options))
{
var customerFromStore = context.Set<Customer>().Single();
Assert.Equal(42, customerFromStore.Id);
Assert.Equal(
"Daenerys",
(string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue);
}
using (var context = new DbContext(options))
{
var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen";
context.Update(customer);
await context.SaveChangesAsync();
}
using (var context = new DbContext(options))
{
var customerFromStore = context.Set<Customer>().Single();
Assert.Equal(42, customerFromStore.Id);
Assert.Equal(
"Daenerys Targaryen",
(string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue);
}
using (var context = new DbContext(options))
{
context.Delete(customer);
await context.SaveChangesAsync();
}
using (var context = new DbContext(options))
{
Assert.Equal(0, context.Set<Customer>().Count());
}
}