我是EntityFramework核心新手。
我有一个DBContext类,它包含所有DBSet对象。我想将所有对象序列化到MongoDB数据库。是否可以将DBSet对象写入mongodb而不将它们转换为List对象。
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Zeiss.IMT.MCCNeo.DataMigration.Utilities
{
public partial class mccdbContext : DbContext
{
public virtual DbSet<AliveInfo> AliveInfo { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=INBLRN0517\SQLEXPRESS;Database=mccdb;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AliveInfo>(entity =>
{
entity.ToTable("ALIVE_INFO");
entity.HasIndex(e => new { e.KmgId, e.System })
.HasName("UQ__ALIVE_IN__130B8EFC0D03FCC7")
.IsUnique();
entity.Property(e => e.Id)
.HasColumnName("ID")
.ValueGeneratedNever();
entity.Property(e => e.BdeEnabled).HasColumnName("BDE_ENABLED");
entity.Property(e => e.FirstMsg).HasColumnName("FIRST_MSG");
entity.Property(e => e.KmgId)
.IsRequired()
.HasColumnName("KMG_ID")
.HasColumnType("varchar(20)");
entity.Property(e => e.LastMsg).HasColumnName("LAST_MSG");
entity.Property(e => e.MessproEnabled).HasColumnName("MESSPRO_ENABLED");
entity.Property(e => e.ObdEnabled).HasColumnName("OBD_ENABLED");
entity.Property(e => e.System)
.IsRequired()
.HasColumnName("SYSTEM")
.HasColumnType("varchar(100)");
});
}
}
目前我正在使用这种方法。我想在表格ALIVE INFO中将mongodb的所有记录批量插入。
class Program
{
static void Main(string[] args)
{
using (var mccdbContext = new mccdbContext())
{
var aliveInfoList = mccdbContext.AliveInfo.ToList();
//converted list is written to mongodb.
}
Console.ReadKey();
}
}
答案 0 :(得分:1)
DbSet继承IEnumerable<TEntity>
(https://msdn.microsoft.com/en-us/library/gg696460(v=vs.113).aspx)。在mongo c#driver中的InsertMany接受IEnumerable<TEntity>
所以也许你可以这样写:
aliveInfoCollection.InsertMany(mccdbContext.AliveInfo as IEnumerable<AliveInfo>)