所以即时通讯寻找提高我的代码升技。 我目前有两个模型和两个连接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(); 我进入并设置我的外部约束,我再次保存我的更改。对我来说,这看起来很违反直觉,因此我问你,因为我相信有一个更聪明的方法来做到这一点?
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?
最满意答案
你需要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(..); } } }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(..); } } }更多推荐
发布评论