问题
So im looking to improve my code abit. I currently have two models and two tables that are connected fk and pk.
I want to insert new attributes into my two tables, but in that same instant, i want to set the fk in my db called USERS
.
Currently i cant find another way other than this:
using (db)
{
var encryptedPassword = PasswordStorage.CreateHash(model.Users.PASSWORD);
var user = db.USERS.Create();
user.EMAIL = model.Users.EMAIL;
user.PASSWORD = encryptedPassword;
user.NAME = model.Users.NAME;
db.USERS.Add(user);
var place = db.PLACES.Create();
place.CITY = model.Places.CITY;
place.PLACE_NAME = model.Places.PLACE_NAME;
place.POSTAL = model.Places.POSTAL;
place.STREET = model.Places.STREET;
place.STREET_NO = model.Places.STREET_NO;
db.PLACES.Add(place);
db.SaveChanges();
var placesId = db.USERS.Where(u => u.EMAIL == model.Users.EMAIL).Select(u => u.PLACES_ID).Single();
placesId = db.PLACES.Where(u => u.PLACE_NAME == model.Places.PLACE_NAME).Select(u => u.id).Single();
db.SaveChanges();
}
So after the first db.SaveChanges();
i go in and set my foreign constraint, and i once again save my changes.. For me, this seems very counterintuitive, and i therefore ask you, because i believe there is a smarter way to do this?
回答1:
You need Code First Migrations i.e. System.Data.Entity.Migrations;
namespace MigrationsDemo.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddFK : DbMigration
{
public override void Up()
{
AddFK(..);
}
public override void Down()
{
RemoveFK(..);
}
}
}
回答2:
since its looks like one to one
relationship then i assume you must have USERS User
in place
model so you can try this
var encryptedPassword = PasswordStorage.CreateHash(model.Users.PASSWORD);
var user = db.USERS.Create();
user.EMAIL = model.Users.EMAIL;
user.PASSWORD = encryptedPassword;
user.NAME = model.Users.NAME;
var place = db.PLACES.Create();
place.CITY = model.Places.CITY;
place.PLACE_NAME = model.Places.PLACE_NAME;
place.POSTAL = model.Places.POSTAL;
place.STREET = model.Places.STREET;
place.STREET_NO = model.Places.STREET_NO;
place.User=user;
db.PLACES.Add(place);
来源:https://stackoverflow.com/questions/42799540/insert-fk-at-the-same-time-as-attributes-are-added