问题描述
所以我希望改善我的代码。我目前有两个模型和两个连接fk和pk的表。
So im looking to improve my code abit. I currently have two models and two tables that are connected fk and pk.
我想在我的两个表中插入新属性,但在同一时刻,我想在我的数据库中设置fk,名为 USERS
。
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();
}
所以第一个 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?
推荐答案
您需要,即 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(..);
}
}
}
这篇关于在添加属性的同时插入fk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!