How do I add a new entity that has a property which references an entity that is already created in a database?
I have a Project
table and a Organization
table.
Project
has a many to one relationship with Organization
.
Project
has a scalar property OrganizationName
that references the primary key Name
in Organization
I have a create view which is strongly typed to the Project
model.
I collect input for the Project.Organization.Name
property like so:
<div class="editor-label">
@Html.Label("Organization Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Organization.Name)
@Html.ValidationMessageFor(model => model.Organization.Name)
</div>
The controller handles the post like so :
[HttpPost]
public ActionResult Create(Project project)
{
if (ModelState.IsValid)
{
开发者_运维知识库 db.Projects.AddObject(project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(project);
}
How can I check to see if the new project.Organization.Name
is already in the database? If it is, I want the new project
to reference that tuple in the database and not attempt to add it again.
- Add a
UNIQUE
constraint to the table. In a multi-user environment, that's the only way to be sure. - If you must know on the client, query the DB.
Like this:
[HttpPost]
public ActionResult Create(Project project)
{
if (ModelState.IsValid)
{
var org = db.Organizations.SingleOrDefault(o => o.Name.Equals(project.Organization.Name, StringComparison.CurrentCultureIgnoreCase));
if (org != null)
{
project.Organization = org;
}
db.Projects.AddObject(project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(project);
}
精彩评论