Update ViewModel with one-to-one relationship by code first - c#

I have 2 table with one-to-one relationship:
public class PersonCall
{
public PersonCall()
{
Destination = new Destination();
}
[Key, ForeignKey("Destination")]
public int DestinationId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Job { get; set; }
public virtual Destination Destination { get; set; }
}
public partial class Destination
{
public int DestinationId { get; set; }
public int? ActivityId { get; set; }
[StringLength(50)]
public string ActivityTextPersian { get; set; }
public int Number { get; set; }
public virtual Activity Activity { get; set; }
public virtual PersonCall PersonCall { get; set; }
}
and a PersonCallViewModel like this:
public class PersonCallViewModel
{
public int DestinationId { get; set; }
[Required(ErrorMessage = "پر کردن این فیلد الزامی است")]
[Display(Name = "نام")]
public string FirstName { get; set; }
[Required(ErrorMessage = "پر کردن این فیلد الزامی است")]
[Display(Name = "نام خانوادگی")]
public string LastName { get; set; }
[Required(ErrorMessage = "پر کردن این فیلد الزامی است")]
[Display(Name = "سمت")]
public string Job { get; set; }
[Required(ErrorMessage = "پر کردن این فیلد الزامی است")]
[Display(Name = "شماره پیجر")]
public int Pager { get; set; }
}
and it's PersonUpdate action in PersonCallController:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PersonUpdate([DataSourceRequest] DataSourceRequest request, PersonCallViewModel personCall)
{
if (personCall != null && ModelState.IsValid)
{
personCallService.Update(personCall);
}
var updateEntity = Json(new[] { personCall }.ToDataSourceResult(request, ModelState)); ;
return updateEntity;
}
My problem is when update Pager property in PersonCallViewModel, database not updated it!
in fact, my grid is updated but when I refresh page or see my table rows in database my value rollback to previous value.
here is my code:
public void Update(PersonCallViewModel personCall)
{
var entity = new PersonCall();
entity.DestinationId = personCall.DestinationId;
entity.Destination.DestinationId = personCall.DestinationId;
entity.FirstName = personCall.FirstName;
entity.LastName = personCall.LastName;
entity.Job = personCall.Job;
entity.Destination.Number = personCall.Pager;
entities.PersonCall.Attach(entity);
entities.Entry(entity).State = EntityState.Modified;
entities.SaveChanges();
}
do you help me?

I solved this problem! thanks of #Henk Holterman for his help!
I create a new object of Destination in Update method and apply changes to that as below:
public void Update(PersonCallViewModel personCall)
{
var entity = new PersonCall();
var entity2 = new Destination();
entity.DestinationId = personCall.DestinationId;
entity.Destination.DestinationId = personCall.DestinationId;
entity.FirstName = personCall.FirstName;
entity.LastName = personCall.LastName;
entity.Job = personCall.Job;
entities.PersonCall.Attach(entity);
var equalDestination = entities.Destination.Where(pd => pd.DestinationId == entity.DestinationId);
foreach (var item in equalDestination)
{
item.Number = personCall.Pager;
}
entity2 = equalDestination.FirstOrDefault();
entities.Destination.Attach(entity2);
entities.Entry(entity).State = EntityState.Modified;
entities.Entry(entity2).State = EntityState.Modified;
entities.SaveChanges();
}

Related

Blazor UI issue, how do I force the required error message on my dropdown select statement when user does not select an option?

I am using Blazor UI. here is my Dropdown markup:
The issue I am referring to is that if the user does NOT make a selection, in other words the _bid.ProductLineId is null and the default "Select a Product Line" is displayed, the [Required] property in the Model (BidViewModel) should fire the message: Product Line is required, but it does not. The on change method is firing, but not the message. Any suggestions?
<ContentTemplate>
<EditForm Model="#_bid" OnValidSubmit="#SaveBid" class="animate-fade" Context="editFrmBidConfirmation">
<DataAnnotationsValidator />
<ServerValidator #ref="serverValidator" />
<ValidationSummary />
<BSContainer>
<BSRow>
<BSCol MD="2" Class="form-label">Product Line:</BSCol>
<BSCol MD="4">
<select id="ProductLine" #onchange="#ProductLineChange" value="#_bid.ProductLineId">
<option value=null>Select a Product Line</option>
#foreach (ProductLine a in _productLines)
{
<option value="#a.Id">#a.Name</option>
}
</select>
</BSCol>
Here is the initialization:
private BidViewModel _bid { get; set; }
private List<Data.Models.ProductLine> _productLines { get; set; }
_productLines = await processor.ProcessObject<List<Data.Models.ProductLine>>(await apiClient.GetProductLinesForUserAsync(userId));
_productLineSelected = (_bid.ProductLineId != null);
Here is the method to fire on change: #ProductLineChange, note "e" is null, thus _bid.ProductLineId is set to null in the BidViewModel.
private async Task ProductLineChange(ChangeEventArgs e)
{
_bid.ProductLineId = e.Value.ToString();
_productLineSelected = (!string.IsNullOrEmpty(_bid.ProductLineId));
if (!string.IsNullOrEmpty(_bid.ProductLineId))
{
_bidClasses = await processor.ProcessObject<List<Bid_Class>>(await apiClient.GetBidClassesAsync(_bid.ProductLineId));
_bidStatuses = await processor.ProcessObject<List<Bid_StatusViewModel>>(await apiClient.GetBidStatusesAsync(_bid.ProductLineId));
_bidTypes = await processor.ProcessObject<List<Bid_Type>>(await apiClient.GetBidTypesAsync(_bid.ProductLineId));
_distributorGroups = new();
_distributors = await processor.ProcessObject<List<DistributorViewModel>>(await apiClient.GetDistributorsByProductLineAsync(_bid.ProductLineId));
}
RefreshScreen(null);
}
Lastly Here is the ViewModel: BidViewModel
public class BidViewModel : Bid
{
public BidViewModel()
{
Notes_Internal = new List<BidNoteInternal>();
Notes_Pricing = new List<BidNotePricing>();
Items = new List<Bid_Item>();
Bid_Locations = new List<Bid_Location>(); //11/30/2021 SEO 681529
Bid_Distributor_Entities = new List<Bid_Distributor_Entity>(); //03/20/2022 SEO 681533
}
// 12/22/2022 PTR 1060058 - Resolve Framework Warning, always start with Capital
public bool IsExisting { get; set; }
public bool Equals(Bid other)
{
if (this.Id == other.Id)
{
return true;
}
else
{
return false;
}
}
}
Bid class which is inherited by BidViewModel:
namespace BQM.Data.Models
{
[Display(Name = "Bid")]
public class Bid : BaseAuditEntity<string>, IValidatableObject
{
public Bid()
{
Id = "Generated";
DateCreated =
DateModified =
Date_BidOpened = DateTime.Now.Date; //09/22/2021 SEO 786208 - Strip time portion to allow for proper filter
Date_BidPriceStart = DateTime.Now;
Distributor_GroupId = "";
DistributorId = "";
Notes_Internal = new List<BidNoteInternal>();
Notes_Pricing = new List<BidNotePricing>();
Items = new List<Bid_Item>();
SalesPeople = new List<BidToSalesPeople>();
IsPercentageOff = false;
Active = true;
IsQuote = false;
PercentageOff = 0;
ProgramAdjustment = false;
//11/30/2021 SEO 681529
Bid_Locations = new List<Bid_Location>();
//03/20/2022 SEO 681533
Bid_Distributor_Entities = new List<Bid_Distributor_Entity>();
}
[Key]
[Required(ErrorMessage = "Bid ID is required.")]
[Display(Name = "New Bid #")]
[Column("BidId")]
[StringLength(10, ErrorMessage = "The New Bid # can only be 10 characters (or less)")]
public override string Id { get; set; }
[Display(Name = "Old Bid #")]
[StringLength(10, ErrorMessage = "The Old Bid # can only be 10 characters (or less)")]
public string OldBidNumber { get; set; }
[Required(ErrorMessage = "Bid Type is required.")]
public string Bid_TypeId { get; set; }
[Display(Name = "Bid Type")]
public virtual Bid_Type Bid_Type { get; set; }
[Required(ErrorMessage = "Bid Class is required.")]
public string Bid_ClassId { get; set; }
[Display(Name = "Bid Class")]
public virtual Bid_Class Bid_Class { get; set; }
[Required(ErrorMessage = "Product Line is required.")]
public string ProductLineId { get; set; }
[Display(Name = "Product Line")]
public virtual ProductLine ProductLine { get; set; }
[Required(ErrorMessage = "Account Name is required.")]
[StringLength(75, ErrorMessage = "Account Name can't be longer than 75 characters")]
public string Account { get; set; }
//09/16/2021 SEO - Added distributed group requirement
[Required(ErrorMessage = "Distributor Group is required.")]
public string Distributor_GroupId { get; set; }
public virtual Distributor_Group Distributor_Group { get; set; }
[Required(ErrorMessage = "Distributor is required.")]
[Display(Name = "Distributor #")]
public string DistributorId { get; set; }
public virtual Distributor Distributor { get; set; }
[Required(ErrorMessage = "Sales Rep. is required.")]
public string SalesPersonDefaultId { get; set; }
[Display(Name = "Sales Rep.")]
public virtual SalesPerson SalesPersonDefault { get; set; }
public virtual List<BidToSalesPeople> SalesPeople { get; set; }
public bool ProgramAdjustment { get; set; }
[Display(Name = "National/Local Programs")]
//[Required(ErrorMessage = "Nat Prg is required.")]
[Column(TypeName = "decimal(5,2)")]
public decimal? Programs { get; set; }
public string Notes_External { get; set; }
public string Notes_External_Footer { get; set; }
public virtual List<BidNotePricing> Notes_Pricing { get; set; }
public virtual List<BidNoteInternal> Notes_Internal { get; set; }
public virtual List<Bid_Item> Items { get; set; } //12/23/2021 SEO Refactor Bid Item Implementation - Changed from Collection To List
[Display(Name = "Bid Opened")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime Date_BidOpened { get; set; }
[Display(Name = "Bid Accepted")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? Date_BidAccepted { get; set; }
[Display(Name = "Bid Expires")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? Date_BidExpires { get; set; }
[Display(Name = "Bid Pricing Start")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? Date_BidPriceStart { get; set; }
[Display(Name = "Bid Pricing End")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? Date_BidPriceEnd { get; set; }
[Display(Name = "Price Esc.")]
public string PriceEscalation { get; set; }
[Display(Name = "Is the Price Guaranteed?")]
[Required(ErrorMessage = "Price Guarantee is required.")]
public bool PriceGuarantee { get; set; }
[Display(Name = "Is this a Percentage Off?")]
[Required(ErrorMessage = "Is Percentage Off is required.")]
public bool IsPercentageOff { get; set; }
[Display(Name = "Percentage Off")]
[Required(ErrorMessage = "Specific Percentage Off is required.")]
[Column(TypeName = "decimal(5,2)")]
public decimal PercentageOff { get; set; }
[Display(Name = "Bid Active")]
[Required(ErrorMessage = "Is Bid Active required.")]
public bool Active { get; set; }
[Display(Name = "Quote?")]
public bool IsQuote { get; set; }
[Required(ErrorMessage = "Bid Status required.")]
public string Bid_StatusId { get; set; }
[Display(Name = "Bid Status")]
public virtual Bid_Status Bid_Status { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!IsQuote && Date_BidAccepted == null)
{
yield return new ValidationResult("You must have an Accepted Date before saving this record as a Bid", new string[] { "Date_BidAccepted" });
}
if (PriceGuarantee && Date_BidPriceEnd == null)
{
yield return new ValidationResult("You must have an End Date for Price Guaranteed bids/quotes", new string[] { "Date_BidPriceEnd" });
}
if (!Active && Date_BidExpires == null)
{
yield return new ValidationResult("You must have an Expire Date for Inactive bids/quotes", new string[] { "Date_BidExpires" });
}
}
//11/30/2021 SEO 681529
public virtual List<Bid_Location> Bid_Locations { get; set; }
//03/20/2022 SEO 681533
public virtual List<Bid_Distributor_Entity> Bid_Distributor_Entities { get; set; }
}
public class BidToSalesPeople : IEquatable<BidToSalesPeople>
{
[Key]
public string BidId { get; set; }
public virtual Bid Bid { get; set; }
[Key]
public string SalesPersonId { get; set; }
public virtual SalesPerson SalesPerson { get; set; }
public bool Equals(BidToSalesPeople other)
{
Contract.Requires(other != null);
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return this.BidId == other.BidId &&
this.SalesPersonId == other.SalesPersonId;
}
public override bool Equals(object obj)
{
return Equals(obj as BidToSalesPeople);
}
public override int GetHashCode()
{
return new Tuple<string, string>(SalesPersonId, BidId).GetHashCode();
}
}
}
Here is the RefreshScreen(null);
private void RefreshScreen(ModalResult modalResult)
{
if (modalResult is null || !modalResult.Cancelled)
{
this.StateHasChanged();
}
}
You question is a bit of a wall of code so I may have missed something important!
There's no such thing as null in html so:
<option value=null>Select a Product Line</option>
actually sets ProductLineId to "null" if selected, which is a valid value for the validator.
Here's some code that I use that "forces" a choice decision on Selects. It's standalone so you can copy and paste it into a page and see it in action.
Once you go to the dropdown you have to choose a value. If you exit without selecting by tabbing no value is set so it's still null and fails validation. Once a value is selected the "-- Select a Product Line --" option disappears.
#page "/"
<PageTitle>Index</PageTitle>
<EditForm Model=this.model>
<DataAnnotationsValidator />
<select class="form-select mb-2" value="#model.ProductLineId" #onchange=this.ProductLineChange>
#if (model.ProductLineId is null)
{
<option disabled selected value="">-- Select a Product Line --</option>
}
#foreach (ProductLine a in _productLines)
{
<option value="#a.Id">#a.Name</option>
}
</select>
<ValidationMessage For="() => this.model.ProductLineId" />
<button class="btn btn-success" type="submit">Submit</button>
</EditForm>
<div>
#model.ProductLineId
</div>
#code {
private Model model = new();
private async Task ProductLineChange(ChangeEventArgs e)
{
this.model.ProductLineId = e.Value?.ToString() ?? null;
// emulate some async work
await Task.Delay(200);
}
public class Model
{
[Required(ErrorMessage = "Product Line is required.")]
public string? ProductLineId { get; set; }
}
private List<ProductLine> _productLines = new()
{
new() { Name = "French" },
new() { Name = "English" },
new() { Name = "Spanish" },
new() { Name = "Swedish" },
};
public record ProductLine
{
public string Id { get; init; } = Guid.NewGuid().ToString();
public string Name { get; init; } = string.Empty;
}
}
You should be able to use this to resolve your problem.

ASP .NET Core MVC - How to initialize an object property in a model class which is a result of many-to-many relationship?

When I want to call a property of my object property Trip from TripApplicationUser model class its values are null. So I do not know how to initialize the Trip object to get its property values later on and to now have problem with indexing in database. I have pasted here the most important parts of code.
[Authorize]
public async Task<ActionResult> Enroll(int id)
{
if (id == null)
{
return NotFound();
}
var currentTrip = await _context.Trip.FindAsync(id);
var currentUser = await _userManager.GetUserAsync(User);
var isAlreadyEnrolled = _context.TripApplicationUsers.Where(tu => tu.ApplicationUserId.Equals(currentUser.Id) && tu.TripId == id);
var UserTrips = isAlreadyEnrolled.ToList();
if (currentTrip.TripSeats > 0 && !UserTrips.Any())
{
ViewBag.process = "done";
currentTrip.TripSeats--;
_context.Update(currentTrip);
var rowToSave = new TripApplicationUser
{
TripId = currentTrip.TripId,
ApplicationUserId = currentUser.Id,
Trip = currentTrip //HOW SHOULD I INITIALIZE IT ACTUALLY?
};
_context.Add(rowToSave);
await _context.SaveChangesAsync();
} else if (UserTrips.Any())
{
ViewBag.process = "already done";
} else if(currentTrip.TripSeats <= 0)
{
ViewBag.process = "not done";
}
var UsersTrips = _context.TripApplicationUsers.Where(t => t.ApplicationUserId.Equals(currentUser.Id)).ToList();
return View(UsersTrips);
}
public class ApplicationUser : IdentityUser
{
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string FirstName { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string Surname { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string BirthDate { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class Trip
{
public int TripId { get; set; }
public string TripDate { get; set; }
public int TripDuration { get; set; }
public int TripLength { get; set; }
public int TripSeats { get; set; }
public int TrailId { get; set; }
public Trail Trail { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class TripApplicationUser
{
public int TripId { get; set; }
public Trip Trip { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
If you want your Trip object to contain data from Navigational properties you have to include them in the request.
var currentTrip = await _context.Trip.Include(trip=> trip.TripApplicationUsers).FirstOrDefaultAsync(trip => trip.TripId == id);

Explicit loading do not loading related entities(list in list)

I try to load from the already found user a list of friends and from the list of friends and load for each list of messages.
dont work
Load only frends, do not load messages in each frend
_context.Entry(ldetails).Collection(p=>p.ListFriends).Query().
Include(r=>r.MessagesDetails).Load();
My data struct
public class RegistrationUser
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PMId { get; set; }
[Required]
[Column(TypeName ="varchar(16)")]
public string UserName { get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string Password { get; set; }
[Column(TypeName = "varchar(480)")]
public string Token { get; set; }
public ICollection<ListFriend> ListFriends { get; set; }
public RegistrationUser()
{
ListFriends = new List<ListFriend>();
}
}
public class ListFriend
{
[Key,Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[Column(TypeName ="varchar(16)")]
public string UserFriendName { get; set; }
public ICollection<MessagesDetail> MessagesDetails { get; set; }
public ListFriend()
{
MessagesDetails = new List<MessagesDetail>();
}
}
public class MessagesDetail
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key,Column(Order = 0)]
public int PMIdMes { get; set; }
[Required]
[Column(TypeName ="nvarchar(240)")]
public string TextMessage{ get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string SenderUser { get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string CatcherUser { get; set; }
}
It my method not work
[HttpPost("EnterUserDetail")]
public async Task<ActionResult<RegistrationUser>> postUserDetail( RegistrationUser registrationUser )
{
var ldetails = _context.RegistrationUsers.SingleOrDefault(c=>c.UserName==registrationUser.UserName);
var pdetails = _context.RegistrationUsers.SingleOrDefault(c=>c.Password==registrationUser.Password);
if (ldetails == null && pdetails == null)
{
return NotFound();
}
//_context.Entry(ldetails).Collection("ListFriends").Load();
_context.Entry(ldetails).Collection(p=>p.ListFriends).Query().Include(r=>r.MessagesDetails).Load();
//_context.Entry(ldetails).Collection("ListFriends").IsLoaded = true;
//await _context.SaveChangesAsync();
return ldetails;
}
You are actually making 3 requests to the database to get the desired result. A better, optimized way to achieve this could be as
[HttpPost("EnterUserDetail")]
public async Task<ActionResult<RegistrationUser>> postUserDetail( RegistrationUser registrationUser)
{
// send one query to database to get the result and include here.
var ldetails = _context.RegistrationUsers.Include(i => i.ListFriends).SingleOrDefault(c => c.UserName == registrationUser.UserName && c.Password == registrationUser.Password);
if (ldetails == null && pdetails == null)
{
return NotFound();
}
return ldetails;
}

Getting 'The instance of entity type 'X'' Exception

I just want to ask why i am getting this error when I am trying to insert multiple data in 2 tables. Thank you for your answer in advanced.
This the the error I am getting in exception handler
This is my Source Code
public void CreateCollection(IEnumerable<CollectionViewModel> p , IEnumerable<Claim> user)
{
var userId = Convert.ToUInt32(user.Single(logon => logon.Type == CustomClaimTypes.UserId).Value);
/*Create access table for insert*/
var modules = p.Select(collection => new Accountcollection
{
AccountId = userId,
Amount = collection.Amount,
CashSource = collection.CashSource,
CollectionDate = collection.CollectionDate,
CreatedDatetime = DateTime.Now,
UpdatedDatetime = DateTime.Now,
}).ToList();
_context.Accountcollection.AddRange(modules);
var calendar_event = p.Select(collection => new Accountcalendarevents
{
AccountId = userId,
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
_context.Accountcalendarevents.AddRange(calendar_event);
_context.SaveChanges();
}
this is my account calendar events entity
public class Accountcalendarevents
{
public long Id { get; set; }
public long AccountId { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string ThemeColor { get; set; }
public bool Isfullday { get; set; }
public string Status { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedDatetime { get; set; }
public long UpdatedBy { get; set; }
public DateTime UpdatedDatetime { get; set; }
}
and my account collection entity
public long Id { get; set; }
public long AccountId { get; set; }
public double? Amount { get; set; }
public string CashSource { get; set; }
public DateTime CollectionDate { get; set; }
public DateTime? CreatedDatetime { get; set; }
public DateTime? UpdatedDatetime { get; set; }
[ForeignKey("AccountId")]
public Accountcalendarevents Accountcalendarevents { get; set; }
}
You may try like this:
_context.Accountcollection.AddRange(modules);
_context.SaveChanges();
.
.
.
_context.Accountcalendarevents.AddRange(calendar_event);
_context.SaveChanges();

.NET Foreign Key Cannot be Inserted

I have used foreign keys many times before and set up these models just the same however I'm getting this error, the error also occurs when writing usertableID:
A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = FK_dbo.Outreaches_dbo.OutreachNames_OutreachNamesID ]
Can anyone explain?
Code causing error:
foreach (var item in records)
{
List<string> foundEmails = EmailScraper.Main(item.domain);
string[] emails = foundEmails.ToArray();
var outreach = new Outreach {
domain = item.domain,
email1 = foundEmails.ElementAtOrDefault(0),
email2 = foundEmails.ElementAtOrDefault(1),
email3 = foundEmails.ElementAtOrDefault(2),
email4 = foundEmails.ElementAtOrDefault(3),
email5 = foundEmails.ElementAtOrDefault(4),
email6 = foundEmails.ElementAtOrDefault(5),
UserTableID = UserTableID,
OutreachNamesID = listNumber
};
db.OutreachLists.Add(outreach);
db.SaveChanges();
}
var outreachlist = new OutreachNames
{
ID = listNumber,
listName = model.listName,
listCount = count,
listSent = 0,
unread = 0,
replyRate = 0,
UserTableID = UserTableID,
};
db.OutreachNames.Add(outreachlist);
db.SaveChanges();
Model Outreach:
namespace Linkofy.Models
{
public class Outreach
{
public int ID { get; set; }
public int? OutreachNamesID { get; set; }
public virtual OutreachNames OutreachNames { get; set; }
public string name { get; set; }
[Required]
public string domain { get; set; }
public string email1 { get; set; }
public string email2 { get; set; }
public string email3 { get; set; }
public string email4 { get; set; }
public string email5 { get; set; }
public string email6 { get; set; }
public string email7 { get; set; }
public string email8 { get; set; }
public int? UserTableID { get; set; }
public virtual UserTable UserTable { get; set; }
}
}
Model OutreachNames:
namespace Linkofy.Models
{
public class OutreachNames
{
public int ID { get; set; }
[Required]
public string listName { get; set; }
public int listCount { get; set; }
public int listSent { get; set; }
public int unread { get; set; }
public int replyRate { get; set; }
public virtual ICollection<Outreach> OutreachLists { get; set; }
public int? UserTableID { get; set; }
public virtual UserTable UserTable { get; set; }
}
}
When saving your Outreach you are setting the FK OutreachNamesID to an ID of a record which doesn't exist yet. You need to create this record first or use Entity Framework to create OutreachNames as a child entity. Both entities need to be persisted to the db in one transaction.
You can create the child entity inside of the parent and persist them in one go like this:
var outreach = new Outreach
{
OutreachNames = new OutreachNames
{
...
}
}
db.OutreachLists.Add(outreach);
db.SaveChanges();

Categories