所以我希望改进我的代码升级。我目前有两个模型和两个连接fk和pk的表。
我想在我的两个表中插入新属性,但在同一时刻,我想在我的数据库中设置名为USERS
的fk。
目前我找不到另外一种方式:
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();
}
所以在第一个db.SaveChanges();
之后我进入并设置我的外国约束,我再次保存我的更改..对我来说,这似乎非常违反直觉,因此我问你,因为我相信有一个更聪明的方法吗?
答案 0 :(得分:0)
因为它看起来像one to one
关系,所以我假设你必须在USERS User
模型中拥有place
,这样你就可以试试这个
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);
答案 1 :(得分:0)
您需要Code First Migrations,即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(..);
}
}
}