如何从实体框架获取自动ID

时间:2016-07-14 12:36:17

标签: c# entity-framework

我想获取我刚刚创建的客户的id以插入到userId表中,这将填充查找表中包含的信息。

我的问题是如何从新造的客户那里检索身份证。我正在使用实体框架6顺便说一句

tblPortalCustomerInfo _customer = new tblPortalCustomerInfo();

_customer.firstName = firstname;
_customer.middleName = middle;
_customer.lastName = lastname;
_customer.IVACODE = ivaCode;
_customer.email = emailAddress;

portalEntities.tblPortalCustomerInfoes.Add(_customer);

tblPortalUser _user = new tblPortalUser();
_user.customerInfo = _customer.id; this is where i need the link?.
_user.EmailAddress = emailAddress;
_user.password = password;
_user.isActive = true;
_user.optinDateStart = DateTime.Now;

portalEntities.tblPortalUsers.Add(_user);
portalEntities.tblPortalUsers.Add(_user);

2 个答案:

答案 0 :(得分:2)

您必须先插入该客户行,然后自动填充为_customer.id生成的主键值,如:

tblPortalCustomerInfo _customer = new tblPortalCustomerInfo();

_customer.firstName = firstname;
_customer.middleName = middle;
_customer.lastName = lastname;
_customer.IVACODE = ivaCode;
_customer.email = emailAddress;

portalEntities.tblPortalCustomerInfoes.Add(_customer);
portalEntities.SaveChanges(); // insert the customer


tblPortalUser _user = new tblPortalUser();
_user.customerInfo = _customer.id; // now you should have primary key value here
_user.EmailAddress = emailAddress;
_user.password = password;
_user.isActive = true;
_user.optinDateStart = DateTime.Now;

答案 1 :(得分:1)

您需要在添加新记录后调用SaveChange()方法,然后您将获得新生成的ID