如何使用Entity框架6将数据插入三个表? [英] How to insert data into three tables using Entity framework 6?

查看:59
本文介绍了如何使用Entity框架6将数据插入三个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将数据插入BankAccount表中。但是无法为我创建两个服务的其他两个表创建它。我也在SQL分析器中看过这个但是当我运行代码将数据插入另外两个表时没有动作。

请帮助!!!!

这是我的控制器:

I am able to insert data into "BankAccount" table. But could not make it for the other two tables for which I created two services. I also watched this in SQL profiler but no action happens when i run the code for inserting data into the two other tables.
Please HELP!!!!
This is my Controller:

[HttpPost]
        public JsonResult CreateNewUser(BankAccount newUser)
        {
            string message = string.Empty;
            if (ModelState.IsValid)
            {
                
                string pswdsalt = PassWord.GenerateSalt();
                string pswd = PassWord.EncodePassword(newUser.Password, 1, pswdsalt);
                newUser.CreatedDate = System.DateTime.Now;
                newUser.Deleted = "N";
                newUser.Password = pswd;
                newUser.PasswordSalt = pswdsalt;
                try
                {
                    db.BankAccounts.Add(newUser);
                    idGeneratorService.UpdateNewAcNo(newUser.AccountNo);
                    balanceService.CreateBalanceDetailsForNewUser(newUser.AccountNo);
                    db.SaveChanges();
                    message = "New User Created Successfully";
                }
                catch (Exception Ex)
                {
                    message = "Oops! Something wrong happened" + Ex.Message;
                }
                
            }
            else
            {
                message = "Oops! Something wrong happened.Please try again after sometime";
            }

            return Json(message, JsonRequestBehavior.AllowGet);
        }



和我的两个服务名为idGeneratorService& balanceService:


and my two Service named "idGeneratorService" & "balanceService" :

public void UpdateNewAcNo(string AcNo)
        {
            TransactionIdGenerator acnoGenerator = new TransactionIdGenerator();
            acnoGenerator.AcNo = AcNo;
            db.SaveChanges();
        }

public void CreateBalanceDetailsForNewUser(string AcNo)
        {
            dailybalance.Id = Guid.NewGuid();
            dailybalance.AcNo = AcNo;
            dailybalance.Date = System.DateTime.Now;
            dailybalance.Balance = 0;
            dailybalance.Deleted = "N";
            db.SaveChanges();
        }

推荐答案

db.BankAccounts.Add(newUser);
//first save bank account 
db.SaveChanges();
//now database will generate primary key for you to use as foreign key for other tables
idGeneratorService.UpdateNewAcNo(newUser.AccountNo);
balanceService.CreateBalanceDetailsForNewUser(newUser.AccountNo);


这篇关于如何使用Entity框架6将数据插入三个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆