Autofill navigation Id property to child class when inserting into database with entity framework

Viewed 74

Let's say I have User and CreditCard classes in online shop application:

User() {
  int Id;
  List<CreditCard>() CreditCards;
}

CreditCard() {
  int Id;
  int UserId:
  virtual User User;
}

User needs at least one CreditCard, and CreditCard requires User. At this moment I'm using following entity type configuration:

For User:

 HasMany(x => x.CreditCards)
   .WithRequired(x => x.User)
   .HasForeignKey(x => x.UserId);

For CreditCard:

 HasRequired(x => x.User)
   .WithRequired(x => x.CreditCards)
   .HasForeignKey(x => x.UserId);

At this moment everything is working fine, but I want to add a way to specify main CreditCard like so:

User() {
  int Id;
  int MainCreditCardId;
  List<CreditCard>() CreditCards;
}

MainCreditCardId is pointing to one of cards from the list.

The problem begins with posting new User to the system - Main credit card is required, but i don't have it's id yet, since it is filled by database itentity. What would be the way to assign this id to MainCreditCardId?

POST model would look like this:

User() {
  int Id;
  CreditCard MainCreditCard;
  List<CreditCard>() CreditCards;
}

And GET one like this:

User() {
  int Id;
  int MainCreditCardId;
  List<CreditCard>() CreditCards;
}

Of course, the models are simplified for the needs of the question

0 Answers
Related