How to add foreign key to entity - c#

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception.
I'm using EF Code first and I'm getting error above when I trying do this:
public ActionResult CreateTransaction(TransactionViewModel model)
{
try
{
if (model.MemberId != 0 && model.SubcategoryId != 0 & model.CategoryId != 0)
{
Transaction t = new Transaction();
t.Amount = model.Amount;
t.Comment = model.Comment;
t.Date = DateTime.Now;
t.TransactionSubcategory = db.Subcategories.Find(model.SubcategoryId);//and i have error in this line
//i tried also this code below but it's the same error
//db.Subcategories.Find(model.SubcategoryId).Transactions.Add(t);
db.Members.Find(model.MemberId).Transactions.Add(t);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("CreateTransaction") ;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return RedirectToAction("CreateTransaction");
}
}
And there is my model
public class Subcategory
{
public Subcategory()
{
IsGlobal = false;
Transactions = new List<Transaction>();
}
public int Id { get; set; }
public string Name { get; set; }
public TransactionType TypeOfTransaction { get; set; }
public Category OwnerCategory { get; set; }
public List<Transaction> Transactions { get; set; }
public bool IsGlobal { get; set; }
}
public class Transaction
{
public int Id { get; set; }
public Decimal Amount { get; set; }
public DateTime Date { get; set; }
public string Comment { get; set; }
public Subcategory TransactionSubcategory { get; set; }
public Member OwnerMember { get; set; }
}
I don't know why thats happen because in database in Transaction table i see there is column with FK.
If you need there is rest of the model
public class Budget
{
public Budget()
{
Members = new List<Member>();
}
public int Id { get; set; }
public string BudgetName { get; set; }
public string OwnerName { get; set; }
public DateTime CreatedTime { get; set; }
public List<Member> Members { get; set; }
}
public class Category
{
public Category()
{
IsGlobal = false;
}
public int Id { get; set; }
public string Name { get; set; }
public List<Subcategory> Subcategories { get; set; }
public Budget OwnerBudget { get; set; }
public bool IsGlobal { get; set; }
}
public class Member
{
public Member()
{
Transactions = new List<Transaction>();
}
public Budget OwnerBudget { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedTime { get; set; }
public List<Transaction> Transactions { get; set; }
}
public enum TransactionType
{
Income,
Expenditure
}

Try adding
public int TransactionSubcategoryId { get; set; }
public int OwnerMemberId { get; set; }
In your Transaction class.

Related

Get All data from two tables in .net 5 web api?

Patient.cs //This is Patient Model Class
namespace HMS.Models
{
public class Patient
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
[JsonIgnore]
public IList<DoctorPatient> DoctorPatients { get; set; }
public InPatient InPatients { get; set; }
public OutPatient OutPatients { get; set; }
}
}
InPatient.cs //This InPatient Model Class
namespace HMS.Models
{
public class InPatient
{
[ForeignKey("Patient")]
public string InPatientId { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
public Patient Patient { get; set; }
}
}
Here Patient and InPatient Attribute have one-to-one relationship
ViewInPatient.cs
namespace HMS.Models
{
public class ViewInPatient
{
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
}
}
Here is my DbContext class
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DoctorPatient>()
.HasOne(x => x.Doctor)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(di => di.DoctorId);
modelBuilder.Entity<DoctorPatient>()
.HasOne(y => y.Patient)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(pi => pi.PatientId);
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<DoctorPatient> DoctorPatients { get; set; }
public DbSet<InPatient> InPatients { get; set; }
//public DbQuery<ViewInPatient> ViewInPatients { get; set; }
}
How to get all data of both Patients and InPatients Table like in ViewInPatient class? (I tried to create a view in sql server but in add table window it shows InPatient instead of InPatients and it return null value)
You can join both models in a Linq expression and return ViewInPatient list:
var ViewInPatient_set =
YourContext
.InPatients
.Select(i=> new ViewInPatient()
{
Name = i.Patient.Name,
// ...
RoomNo = i.RoomNo,
// ...
}
)
.ToList(); // <-- transform to list is optional

Entity Framework 6.1: update child ICollection when the parent entity is created

I have to pass some data from a source DB to another target DB both handled using Entity Framework just with two different DbContexts.
This is my code:
internal async static Task UploadNewsList(DateTime dataStart, TextWriter logger)
{
try
{
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
using (BDContentsDataModel buffettiContext = new BDContentsDataModel())
{
List<News> newsList = buffettiContext.News.Where(x => x.Online && x.DataPub >= dataStart.Date).ToList();
using (DirectioDBContext directioContext = new DirectioDBContext())
{
foreach(News buffettiNews in newsList)
{
bool hasAuth = false;
List<DirectioAutore> listAutori = null;
List<DirectioAutore> listAutoriFinal = new List<DirectioAutore>();
if (buffettiNews.AutoreList?.Count > 0)
{
hasAuth = true;
listAutori = EntitiesHelper.GetAutoriDirectio(buffettiNews.AutoreList.ToList(), directioContext);
foreach (var autore in listAutori)
{
int dirAuthId = 0;
bool exist = false;
foreach (var dirAut in directioContext.Autori)
{
if (dirAut.Nome.IndexOf(autore.Nome, StringComparison.InvariantCultureIgnoreCase) >= 0 &&
dirAut.Cognome.IndexOf(autore.Cognome, StringComparison.InvariantCultureIgnoreCase) >= 0)
{
exist = true;
dirAuthId = dirAut.Id;
}
}
//directioContext.Autori.
//Where(x => autore.Cognome.ToLowerInvariant().Contains(x.Cognome.ToLowerInvariant()) &&
// autore.Nome.ToLowerInvariant().Contains(x.Nome.ToLowerInvariant())).Any();
if (!exist)
{
directioContext.Autori.Add(autore);
directioContext.SaveChanges();
}
else
{
autore.Id = dirAuthId;
}
listAutoriFinal.Add(autore);
}
}
DirectioNews directioNews = EntitiesHelper.CreateDirectioNewsModel(buffettiNews);
if (hasAuth)
directioNews.AutoreList = listAutoriFinal;
if (directioNews == null)
throw new Exception("[News] - Trasformazione entità fallita");
directioContext.News.Add(directioNews);
await directioContext.SaveChangesAsync();
}
}
}
}
catch (Exception ex)
{
logger.WriteLine(ex.Message);
throw ex;
}
}
This is the target DbContext:
public class DirectioDBContext : DbContext
{
public DirectioDBContext() : base("name=DirectioCMSDataModel") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// ...
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("Autore_Id");
cs.MapRightKey("News_Id");
cs.ToTable("NewsAutore");
});
}
public virtual DbSet<DirectioNews> News { get; set; }
public virtual DbSet<DirectioVideo> Video { get; set; }
public virtual DbSet<DirectioMedia> Media { get; set; }
public virtual DbSet<DirectioAutore> Autori { get; set; }
public virtual DbSet<DirectioVideoAutori> VideoAutori { get; set; }
}
This is the interested target Parent Model:
[Table("News")]
public partial class DirectioNews
{
[Key]
public int Id { get; set; }
public string Titolo { get; set; }
public int IdDocType { get; set; }
public string Abstract { get; set; }
public string Testo { get; set; }
[Required]
public DateTime DataPub { get; set; }
public int IdUmbraco { get; set; }
public int CreatedById { get; set; }
public DateTime CreateDate { get; set; }
public int? UpdateById { get; set; }
public DateTime? UpdateDate { get; set; }
public int? DeletedById { get; set; }
public DateTime? DeletedDate { get; set; }
public int? ResumedById { get; set; }
public DateTime? ResumedDate { get; set; }
public int? PublishedById { get; set; }
public DateTime? PublishedDate { get; set; }
public int? UnpublishedById { get; set; }
public DateTime? UnpublishedDate { get; set; }
public DateTime? PublishedFrom { get; set; }
public DateTime? PublishedTo { get; set; }
public bool Online { get; set; }
public bool APagamento { get; set; }
public int IdConsulenzaOld { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<DirectioAutore> AutoreList { get; set; }
public bool IsFromOtherCMS { get; set; } = false;
public string Name { get; set; }
public int? NodeId { get; set; }
public int SortOrder { get; set; } = 0;
public Guid PlatformGuid { get; set; }
public Guid SourceGuid { get; set; }
// Permette l'accesso anche senza login
public bool FreeWithoutLogin { get; set; }
// nasconde dalla visualizzazione della lista normale del frontend, visibile solo attraverso l'etichetta campagna
public bool HideFromList { get; set; }
#region parametri per riferimenti temporali
public int? Day { get; set; } = null;
public int? Month { get; set; } = null;
public int? Year { get; set; } = null;
#endregion
public int? MediaId
{
get; set;
}
}
And this is the target Child model
[Table("Autori")]
public class DirectioAutore
{
[Key]
public int Id { get; set; }
public string Nome { get; set; }
[Required]
public string Cognome { get; set; }
public string DescrizioneBreve { get; set; }
public string Descrizione { get; set; }
public string Email { get; set; }
public string Immagine { get; set; }
public string Tipo { get; set; } // Maschio Femmina Team
public string Twitter { get; set; }
public int IdUmbraco { get; set; }
public bool Online { get; set; }
public DateTime? PublishedFrom { get; set; }
public DateTime? PublishedTo { get; set; }
public int IdOld { get; set; }
public bool IsDeleted { get; set; }
public int? NodeId { get; set; }
public string Name { get; set; }
public int CreatedById { get; set; } = 1;
public DateTime CreateDate { get; set; }
public int? UpdateById { get; set; }
public DateTime? UpdateDate { get; set; }
public int? DeletedById { get; set; }
public DateTime? DeletedDate { get; set; }
public int? ResumedById { get; set; }
public DateTime? ResumedDate { get; set; }
public int? PublishedById { get; set; }
public DateTime? PublishedDate { get; set; }
public int? UnpublishedById { get; set; }
public DateTime? UnpublishedDate { get; set; }
public string MetaaDescrBreve { get; set; }
public int? MediaId
{
get; set;
}
public Guid PlatformGuid { get; set; }
public Guid SourceGuid { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public virtual ICollection<DirectioNews> News { get; set; }
}
EntityFramework generated this table to handle this many-to-many relation:
When it saves the entity, it goes into the catch statement and show this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.NewsAutore_dbo.Autori_Autore_Id". The conflict occurred in database "DirectioContentsCMS_Stage_20201102", table "dbo.Autori", column 'Id'
What could be the problem?
Thank you so much
[SOLVED]
I was wrongly pointing LeftKey and RightKey into the DbContext, they was not pointing to the correct FKs.
I just inverted FKs:
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("Autore_Id");
cs.MapRightKey("News_Id");
cs.ToTable("NewsAutore");
});
instead of
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("News_Id");
cs.MapRightKey("Autore_Id");
cs.ToTable("NewsAutore");
});
Because MapLeftKey points to the parent entity of the navigation property specified in the HasMany method and MapRightKey points to the parent entity of the navigation property specified in the WithMany. I was doing exactly the opposite.
Then i moved the association after actually saving the news to prevent multiple authors creation:
// ...
DirectioNews directioNews = EntitiesHelper.CreateDirectioNewsModel(buffettiNews);
if (directioNews == null)
throw new Exception("[News] - Trasformazione entità fallita");
directioContext.News.Add(directioNews);
directioContext.SaveChanges();
if (hasAuth)
{
List<int> ids = listAutori.Select(s => s.Id).ToList();
List<DirectioAutore> r = directioContext.Autori.Where(x => ids.Contains(x.Id)).ToList();
directioNews.AutoreList = r;
directioContext.SaveChanges();
}

Getting Stackoverflow exception when mapping using automapper

I am getting StackOverflow exception while passing the objects using automapper.
This is before mapping getting result accurately
Here is the error where exception comes when mapping
My Domain Model class is
public class Appointment
{
[Key]
public int AppointmentID { get; set; }
public int Serial { get; set; }
public int AppointmentTypeID { get; set; } = 2;
public DateTime CreatedAt { get; set; }
public string CreatedBy { get; set; }
public DateTime? UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
[ForeignKey("CreatedBy")]
public virtual User User { get; set; }
public virtual ICollection<VisitRequest> VisitRequests { get; set; }
[ForeignKey("AppointmentTypeID")]
public virtual VisitPurpose VisitPurpose { get; set; }
public virtual ICollection<AppointmentStatus> AppointmentStatuses { get; set; }
}
My View Model Classes are
public class ApproveAppointmentViewModel
{
[Key]
public int AppointmentID { get; set; }
public int Serial { get; set; }
public int AppointmentTypeID { get; set; }
public virtual ICollection<ApproveAppointmentVisitRequestViewModel> VisitRequests { get; set; }
public virtual ICollection<ApproveAppointmentStatusViewModel> AppointmentStatuses { get; set; }
}
public class ApproveAppointmentVisitRequestViewModel
{
[Key]
public int VisitRequestID { get; set; }
public bool SendSMS { get; set; }
public int? PurposeID { get; set; }
public string PurposeDescription { get; set; }
public string Attachment { get; set; }
public int VisitorID { get; set; }
public int? AppointmentID { get; set; }
public virtual ApproveAppointmentViewModel Appointment { get; set; }
public virtual ApproveAppointmentVisitorViewModel Visitor { get; set; }
}
public class ApproveAppointmentVisitorViewModel
{
[Key]
public int? VisitorID { get; set; }
public string NationalID { get; set; }
public string FullName { get; set; }
public int Gender { get; set; }
public string Job { get; set; }
public string Type { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public virtual ICollection<ApproveAppointmentVisitRequestViewModel> VisitRequests { get; set; }
}
public class ApproveAppointmentStatusViewModel
{
public int StatusID { get; set; }
public int AppointmentID { get; set; }
public int StatusCode
{
get
{
return 1;
}
}
public DateTime ValidFrom
{
get
{
return DateTime.UtcNow.AddHours(3);
}
}
[UnavailableDate]
public DateTime? AppointmentDateTime
{
get
{
if (AppointmentDate != null)
{
if (AppointmentTime != null && AppointmentTime.Length > 0)
return new DateTime(AppointmentDate.Value.Year, AppointmentDate.Value.Month, AppointmentDate.Value.Day, int.Parse(AppointmentTime.Split(':')[0]), int.Parse(AppointmentTime.Split(':')[1]), 0);
else
return new DateTime(AppointmentDate.Value.Year, AppointmentDate.Value.Month, AppointmentDate.Value.Day);
}
else
{
return null;
}
}
}
public DateTime? AppointmentDate { get; set; }
public DateTime? _AppointmentDate { get; set; }
[Display(Name = "التاريخ")]
public string AppointmentDateHijri
{
get
{
if (AppointmentDate.HasValue)
return AppointmentDate.Value.ConvertToHijriString();
return null;
}
set
{
if (value != null)
{
var generalDate = new DateTime(int.Parse(value.Split('/')[0]), int.Parse(value.Split('/')[1]), int.Parse(value.Split('/')[2]));
AppointmentDate = generalDate.Year > 1500 ? generalDate : generalDate.ConvertToGeorgian();
}
else
AppointmentDate = null;
}
}
[Display(Name = "ملاحظة الإعتماد")]
public string StatusNote { get; set; }
[Required(ErrorMessage = "يجب تحديد الوقت المعتمد")]
[Display(Name = "الوقت")]
public string AppointmentTime { get; set; }
[Range(0, 60, ErrorMessage = "أقل مدة للزيارة 10 دقائق واقصى مدة 60 أو مفتوح")]
[Display(Name = "المدة (دقائق)")]
public int? AppointmentDuration { get; set; }
public virtual ApproveAppointmentViewModel Appointment { get; set; }
}
Controller code is
var AppointmentRequest = db.Appointments.Where(p => p.AppointmentID == id).Include(m => m.VisitRequests).Include(m => m.AppointmentStatuses).FirstOrDefault();
here i am getting exception when mapping using automapper
var vmodel = Mapper.Map<ApproveAppointmentViewModel>(AppointmentRequest);

Entity framework core: Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF

I'm bulding an application and when I want to insert a form into my form table I get the following error:
Cannot insert explicit value for identity column in table 'Relation'
when IDENTITY_INSERT is set to OFF.
These are my models:
Form model:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("FormType")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }
[ForeignKey("FormStatusType")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }
[ForeignKey("Relation")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }
[ForeignKey("Relation")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }
public String SupplierReference { get; set; }
public Guid ApiId { get; set; }
public DateTime DueDate { get; set; }
public FormFile FormFiles { get; set; }
public String FormName { get; set; }
public DateTime UploadDate { get; set; }
Relation model:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("FormType")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }
[ForeignKey("FormStatusType")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }
[ForeignKey("Relation")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }
[ForeignKey("Relation")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }
public String SupplierReference { get; set; }
public Guid ApiId { get; set; }
public DateTime DueDate { get; set; }
public FormFile FormFiles { get; set; }
public String FormName { get; set; }
public DateTime UploadDate { get; set; }
My context looks like this:
public class DataContext: DbContext
{
public DataContext(DbContextOptions<DataContext> options): base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer();
}
public DbSet<Relation> Relation { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<Notification> Notification { get; set; }
public DbSet<FormStatusType> FormStatusType { get; set; }
public DbSet<File> File { get; set; }
public DbSet<FormFile> FormFile { get; set; }
public DbSet<FormType> FormType { get; set; }
public DbSet<Form> Form { get; set; }
public DbSet<User> User { get; set; }
public DbSet<RelationUser> RelationUser { get; set; }
public DbSet<SupplierCustomer> SupplierCustomer { get; set; }
}
The method I use to add a form looks like this:
public async Task<Form> AddForm(Form form, int currentUserId)
{
try
{
if (form != null)
{
//huidige gebruiker als supplier aanduiden
Relation r = await GetCurrentUser(currentUserId);
form.Supplier = r;
form.SupplierId = r.Id;
//form aan de db toevoegen
_datacontext.Form.Add(form);
_datacontext.SaveChanges();
return form;
}
else
{
return null;
}
}
catch (Exception e)
{
LogError(e);
return null;
}
}
The get current user method
private async Task<Relation> GetCurrentUser(int currentUserId)
{
var relation = from r in _datacontext.RelationUser
where r.UserId == currentUserId
select r.Relation;
return await relation.FirstOrDefaultAsync();
}
This is where I call the AddForm method:
[HttpPost]
[Route("addform")]
[Authorize]
// api/form/addform
public async Task<IActionResult> AddForm([FromBody] Form form)
{
if (ModelState.IsValid)
{
Form f = await _formRepository.AddForm(form, GetUserIdFromToken());
if(f != null)
{
QueueObject qo = new QueueObject()
{
ActionTypeId = 1,
FormId = f.Id
};
await new QueueHandler().SendMessageToQueue(qo);
}
return Ok(f);
}
else
{
return NotFound("model is niet geldig");
}
}
I already searched but found nothing that solved the problem
Another possible reason this may happen, is if you have a timeout in some call to SaveChanges when trying to insert new entities to your database, then try calling SaveChanges again, using the same DbContext instance.
This is reproducible:
using(var context = new MyDbContext())
{
context.People.Add(new Person("John"));
try
{
// using SSMS, manually start a transaction in your db to force a timeout
context.SaveChanges();
}
catch(Exception)
{
// catch the time out exception
}
// stop the transaction in SSMS
context.People.Add(new Person("Mike"));
context.SaveChanges(); // this would cause the exception
}
This last SaveChanges would cause Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF.
You have multiple errors on your model. The ForeignKey attribute must point to properties in the class, not to the type of the dependent entity:
//FORM MODEL
[ForeignKey("Type")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }
[ForeignKey("StatusTknype")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }
[ForeignKey("Supplier")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }
[ForeignKey("Customer")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }
//RELATION MODEL
[ForeignKey("Type")]
public int? TypeId { get; set; }
public virtual FormType Type { get; set; }
[ForeignKey("StatusTknype")]
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusTknype { get; set; }
[ForeignKey("Relation")]
public int? SupplierId { get; set; }
public virtual Relation Supplier { get; set; }
[ForeignKey("Customer")]
public int? CustomerId { get; set; }
public virtual Relation Customer { get; set; }
Also, if you followed Convention Over Configuration, you could drop the ForeignKeyAttribute completely by just naming the properties conventionally:
public int? StatusTypeId { get; set; }
public virtual FormStatusType StatusType { get; set; }

How do I post a one-to-many relationship?

Pretty new to ASP.NET and programming. I have two models, two API controllers, two repositories. How do I post the data to the second model while attaching it to the first (I'm guessing by ID.) Do I possibly need a View Model? Also reading a little about unit of work. Maybe neither are necessary? Below is some code. Thanks!
Record.cs
namespace Train.Models {
public class Record {
public int Id { get; set; }
public int Quantity { get; set; }
public DateTime DateCreated { get; set; }
public bool IsActive { get; set; }
public string UserId { get; set; }
public virtual ICollection<Cars> Cars { get; set; }
}
}
Cars.cs
namespace Train.Models {
public class Cars {
public int Id { get; set; }
public string EmptyOrLoaded { get; set; }
public string CarType { get; set; }
//Hopper, flatbed, tank, gondola, etc.
public string ShippedBy { get; set; }
//UP(Union Pacific) or BNSF
public string RailcarNumber { get; set; }
//public virtual ApplicationUser ApplicationUser { get; set; }
public string UserId { get; set; }
public string RecordId { get; set; }
public virtual Record Record { get; set; }
}
}
Record Repository
public void SaveRecord(Record recordToSave) {
if (recordToSave.Id == 0) {
recordToSave.DateCreated = DateTime.Now;
_db.Record.Add(recordToSave);
_db.SaveChanges();
} else {
var original = this._db.Record.Find(recordToSave.Id);
original.Quantity = recordToSave.Quantity;
original.IsActive = true;
_db.SaveChanges();
}
}
EFRepository (Cars)
public void SaveCar(Cars carToSave) {
if (carToSave.Id == 0) {
_db.Cars.Add(carToSave);
_db.SaveChanges();
} else {
var original = this.Find(carToSave.Id);
original.EmptyOrLoaded = carToSave.EmptyOrLoaded;
original.CarType = carToSave.CarType;
original.ShippedBy = carToSave.ShippedBy;
original.RailcarNumber = carToSave.RailcarNumber;
_db.SaveChanges();
}
}

Categories