我有一个员工控制器并尝试将记录添加到MongoDB中的员工文档中。但问题是记录只插入了一次。当我添加新记录时,它不会插入。
这是我的代码
public class Employee
{
[BsonId]
public ObjectId EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
public ActionResult Create()
{
return View(new Employee());
}
控制器
[HttpPost]
public ActionResult Create(Employee employee)
{
var collection = GetEmployeeCollection();
collection.CreateIndex(new IndexKeysBuilder().Ascending("EmployeeNameUnique"), IndexOptions.SetUnique(true));
collection.Insert(employee);
return RedirectToAction("Index");
}
public MongoCollection<Employee> GetEmployeeCollection()
{
var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDBConnection"].ConnectionString);
var server = MongoServer.Create(con);
var db = server.GetDatabase(con.DatabaseName);
return db.GetCollection<Employee>("employee");
}
答案 0 :(得分:0)
问题是因为唯一的名称约束。我放弃了约束,它工作正常。
collection.DropAllIndexes()