Insert fk at the same time as attributes are added

你。 提交于 2019-12-25 16:51:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!