I am new to entity framework and started developing first application using DB first approach , I have added all records in ZipTable and now struggling to add records in CustomerTable after reading data from .csv file.
CustomerTable( Phone[PK],FirstName,LastName,Address,Zip[FK] )
ZipTable( Zip[PK],City,County )
//Class Automatically Generated by EF
public partial class dbzipcode
{
public dbzipcode()
{
this.dbcustomers = new HashSet<dbcustomer>();
}
public string ZIP { get; set; }
public string CITY { get; set; }
public string COUNTY { get; set; }
public virtual ICollection<dbcustomer> dbcustomers { get; set; }
}
public partial class dbcustomer
{
public string PHONE { get; set; }
public string FIRSTNAME { get; set; }
public string LASTNAME { get; set; }
public string ADDRESS { get; set; }
public string ZIP { get; set; }
public virtual dbzipcode dbzipcode { get; set; }
}
I already have the data in DB for ZipCodes Now when i try to add data in CustomerTable i face forignkey error, I want that in Customer zip should be inserted if corresponding Zip exists in secondry table otherwise it should throw exception.
To acheive this i am first reading Zip data from csv before inserting each record. I believe this is not the right way, can someone point me in the right direction ?
dbcustomer customer = new dbcustomer();
customer.PHONE = splits[columnIndexPhoneNumber];
customer.FIRSTNAME = splits[columnIndexFirstName];
customer.LASTNAME = splits[columnIndexLastName];
customer.ADDRESS = splits[columnIndexAddress];
customer.ZIP = splits[columnIndexZipCode];
//dbzipcode z = new dbzipcode() { ZIP=customer.ZIP};
dbzipcode z = ZipCodeDbHandler.GetInstance().GetZipCodeFromDb(splits[columnIndexZipCode]);
customer.dbzipcode = z;
you have customer table , and zip table ,
i'm going to record new customer has zip code not found in my zip code table , so you set general zip or none , or make the ability to add the new zip code before complete record , its ok no wrong way ( it will be wrong if the has complete zip code in zip table and customer can not be outside of this ) , so option : record in customer table and if zip code recorded not in the zip table then do exception and ask to confirm record zip code , or alert must enter valid zip code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.