简体   繁体   中英

Cannot link two tables; mysql; entity framework c#

I have 3 tables : "userDetails", "address" and "country". "UserDetails" and "address" have 1 to 0..1 relationship, "country" and "address" have 1 to many relationship, "country" table is already filled and "userDetails" has 1 random record.

Now, when I want to add a random record into address, i need to have a link on the "userDetails" and "country". I send link on userDetails record as parameter to my createAddress method, so i can take his id, and EF automaticly adds that record to virtual foreign key field.

But how can i get random record from "country"? I can get random id, but EF doesnt add country recoed with that id. As you can see on screenshot userDetails field is filled and country fied is null.

  private address createAddress(userdetails userDetails) { address newAddress = new address(); newAddress.addressLine = getRandomString(20); newAddress.city = getRandomString(10); newAddress.postalCode = getRandomInt(6); newAddress.idaddress = userDetails.iduserDetails; newAddress.countryId = randomizer.Next(1,196); //newAddress.country = (country)(from a in db.country where a.idcountry == newAddress.countryId select a); db.address.Add(newAddress); db.SaveChanges(); return newAddress; } 

在此处输入图片说明

And here is model of these tables, if it can help you understand my problem. 在此处输入图片说明

Have you checked if record is saved in database? newAdress is just an object and I don't think you should expect that it updates field country when you set field countryId.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM