Subsonic 3.0.0.5 Migration Row Update - sql-server

I want to update a table row and I have a following Code
void updatePrimaryPaymentAndSecondaryPaymentSourceTypes()
{
LookUpDetails lookUpDetail = new LookUpDetails();
var repo = new SimpleRepository("E2Lending", SimpleRepositoryOptions.RunMigrations);
lookUpDetail = repo.Single(80);
lookUpDetail.Col1Value = "My Checking Account";
repo.Update(lookUpDetail);
}
public class LookUpDetails
{
[SubSonicPrimaryKey]
public int LookUpDetailId {get; set;}
public int LookUpGroupId { get; set; }
public string Code { get; set; }
public int SortOrder { get; set; }
public string Col1Value { get; set; }
[SubSonicNullString]
public string Col2Value { get; set; }
[SubSonicNullString]
public string Col3Value { get; set; }
[SubSonicNullString]
public string Col4Value { get; set; }
[SubSonicNullString]
public string Col5Value { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public Boolean IsActive { get; set; }
}
When I execute then repo.Update(lookUpDetail); shows me Null reference Exception.
Can you please tell me How I will be able to update a single record in a table?
Regards

I have the very same problem with very simple model class:
class Person
{
public long ID {get;set;}
public string Name { get; set;}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection) {
Person toUpdate = Repository.All<Person>().Single(p => p.ID == id);
TryUpdateModel(toUpdate, collection.ToValueProvider());
Repository.Update(toUpdate); //throws nullreferenceexception
return RedirectToAction("Index");
}
stack trace:
at SubSonic.Query.Update.GetCommand()
at SubSonic.Query.Update.Execute()
at SubSonic.Repository.SimpleRepository.Update[T](T item)
at MvcApplication1.Controllers.PersonController.Edit(Int32 id, FormCollection collection)
in H:\...\Controllers\PersonController.cs:line 71"
My configuration: SubSonic 3, SQLite, empty database

I ran into this problem as well and I was able to download the latest SubSonic source and the issue was already fixed. Just open the SubSonic.Core project and do a build and replace your project's reference to SubSonic.Core.
Download Latest Source
http://github.com/subsonic/SubSonic-3.0
Boom - Repository Update works again!

Related

Error saving DbContext Entity Framework Core

I'm using EF Core and my context is configured with SQL Server. When I to call context.SaveChangesAsync I get the following error message:
Failed executing DbCommand (3,643ms) [Parameters=[#p0='?' (Size = 4000), #p1='?' (DbType = Int32), #p2='?' (Size = 4000), #p3='?' (Size = 4000), #p4='?' (DbType = DateTime2), ...
And the inner exception is:
Operand type clash: datetime2 is incompatible with text
Does anyone know what this means?
For context, this is my DbContext:
public class ComparisonInfoContext : DbContext
{
public DbSet<ComparisonInfo> Comparisons { get; set; } = null!;
public ComparisonInfoContext(DbContextOptions<ComparisonInfoContext> options)
: base(options)
{
}
}
And this is ComparisonInfo (the entity it the DbSet).
public class ComparisonInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string User { get; set; }
public DateTime InitiatedDateTime { get; set; }
public string TaskName { get; set; }
public string Job { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Client { get; set; }
public string Version1 { get; set; }
public string Version2 { get; set; }
public string ControlDb1 { get; set; }
public string ControlDb2 { get; set; }
public string Org { get; set; }
public JobStatus VersionStatus1 { get; set; }
public JobStatus VersionStatus2 { get; set; }
public ComparisonResult ComparisonResult { get; set; }
public List<DiscrepancyInfo> DiscrepancyInfos { get; set; } = new List<DiscrepancyInfo>();
public bool HasBeenPassedToComparePay { get; set; } = false;
}
And lastly here is DiscrepancyInfo (ComparisonInfo stores a list of this):
public class DiscrepancyInfo
{
public int Id { get; set; }
public int? EmployeeId { get; set; }
public DateTime date { get; set; }
//this is an enum
public DiscrepancyPattern DiscrepancyPattern { get; set; }
}
At the moment I am trying to save, the DbSet contains only a single instance of ComparisonInfo and the instance's list of DiscrepancyInfo's is empty.
The issue was happening because I was previously using SqlLite instead of SqlServer. All the migrations were made for SqlLite and deleting them fixed the issue.

SQL Server the column name is specified more than once in the set clause. Entity framework issue

When I do an insert using EF6, I get this error
The column name 'employee_id' is specified more than once in the SET clause. A column cannot be assigned more than one value in the same SET clause. Modify the SET clause to make sure that a column is updated only once. If the SET clause updates columns of a view, then the column name 'employee_id' may appear twice in the view definition
My models looked like this:
public class Entity
{
public Entity()
{
IsActive = true;
IsDeleted = false;
DateCreated = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public int CompanyID { get; set; }
public int SubID { get; set; }
public DateTime DateCreated { get; set; }
public bool IsTransient()
{
return EqualityComparer<long>.Default.Equals(ID, default(long));
}
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
}
public partial class NextOfKin : Entity
{
[Required]
public long employee_id { get; set; }
[StringLength(100)]
[Required]
public string nok_first_name { get; set; }
[StringLength(100)]
[Required]
public string nok_last_name { get; set; }
[StringLength(300)]
[Required]
public string nok_address { get; set; }
[StringLength(100)]
public string nok_email { get; set; }
[StringLength(100)]
public string nok_phone { get; set; }
[StringLength(100)]
public string nok_employer { get; set; }
[StringLength(300)]
public string nok_work_address { get; set; }
[StringLength(100)]
[Required]
public string nok_relationship { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee : Entity
{
//Person Records
public long UserId { get; set; }
public int TitleId { get; set; }
public int? ReligionId { get; set; }
public string SerialNo { get; set; }
[StringLength(100)]
[Required]
public string FirstName { get; set; }
[StringLength(100)]
[Required]
public string LastName { get; set; }
}
My insert code into next of kin was like this.
NextOfKin nextOfKin = new NextOfKin();
nextOfKin.employee_id = newEmployee.ID;
nextOfKin.nok_first_name = "Friday";
nextOfKin.nok_last_name = "Ben";
nextOfKin.nok_address = "XXX";
nextOfKin.nok_email = "xa#xo.com";
nextOfKin.nok_phone = "023938494";
nextOfKin.nok_employer = "50 Queens Street";
nextOfKin.nok_work_address = "51 Queens Street";
nextOfKin.nok_relationship = "Neighbour";
db.NextOfKins.Add(nextOfKin);
db.SaveChanges();
I got an error like this using EF Core
'PropertyNameID' is specified more than once in the SET clause or
column list of an INSERT. A column cannot be assigned more than one
value in the same clause. Modify the clause to make sure that a column
is updated only once. If this statement updates or inserts columns
into a view, column aliasing can conceal the duplication in your code.
It turned out that I had the case wrong in my relatonship
In My business object I had the foreign key set with the wrong case.
public int PropertyNameID { get; set; }
[ForeignKey("PropertyNameId")] public virtual PropertyNameExt PropertyName { get; set; }
Should have been
[ForeignKey("PropertyNameID")] public virtual PropertyNameExt PropertyName { get; set; }
To fix this, remove the relationship on next of kin model, then do migration.
To remove, remove public virtual Employee Employee { get; set; } from NextOfKin model.
The reason for this issue is as follow:
Relationships are only created properly if you name the reference property properly. In this case you should use EmployeeID instead of employee_id for the relationship between next of kin and employee.
The Employee model does not have a link back to the next of kin model. If it's a one to many you can add the property below to the Employee model.
public virtual List NextOfKins{get; set;} //if you need lazy loading
or
public List NextOfKins{get; set;} //if you don't need lazy loading

Web ApI Entity Framework (Code First) Value not appearing in database

My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL".
I have a reports and a bookings tables.
This is the code for the reports:
public class Report
{
public Report()
{
Injuries = new List<Injury>();
this.Bookings = new HashSet<Booking>();
}
public int Id { get; set; }
public string Club1 { get; set; }
public string Club2 { get; set; }
public virtual ICollection<Injury> Injuries { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings:
public class Booking
{
//public Booking()
//{
// Reports = new List<Report>();
//}
public int Id { get; set; }
public string Club { get; set; }
public string PlayerName { get; set; }
public string PlayerNumber { get; set; }
public string Reason { get; set; }
public string Description { get; set; }
//public int? Report_Id { get; set; }
public Nullable<int> Report_Id { get; set; }
public virtual Report Report { get; set; }
//public virtual ICollection<Report> Reports { get; set; }
}
Controller:
//POST: api/Reports
[ResponseType(typeof(Report))]
public async Task<IHttpActionResult> PostReport(Report report)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Reports.Add(report);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
}
I put the test information via Postman:
I'm not sure why Report_Id is showing as it's not required, however, Report_Id1 is the field that is connecting the Report and Booking together.
Since your foreign key doesn't follow convention (ReportId), you need to use the annotation [ForeignKey] or a fluent api configuration:
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Report)
.WithMany(b => b.Bookings)
.HasForeignKey(p => p.Report_Id);
That is why EF is adding the second Report_ID1. https://msdn.microsoft.com/en-us/data/hh134698.aspx

I'm using EF in my application. I try to save\insert a new record to a Patient View

I made a view in SQL server and then added to to my edmx file in visual studio 2012 I then went to POST it on Postman and got this runtime error.
Unable to update the EntitySet 'ViewPatient' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
//Controller action code namespace MvcWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class ViewPatient
{
public int PatientID { get; set; }
public int MedicationID { get; set; }
public int GPID { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public System.DateTime DOB { get; set; }
public string Medication { get; set; }
public string Alergies { get; set; }
public string MedicationHistory { get; set; }
}
}
You need a primary key on the view. http://blogs.msdn.com/b/alexj/archive/2009/09/01/tip-34-how-to-work-with-updatable-views.aspx

ASP.NET MVC 3, SQL Server

First I'll show you what I do, and that there is. My project in ASP.NET MVC 3.
This is model for table Business.
[Table("Business")]
public class Business
{
[Key]
public long? BusinessId { get; set; }
public Int32 LegalTypeId { get; set; }
public Int16 BusinessTypeId { get; set; }
public Int64 OwnerId { get; set; }
public Int32 MainIndustryFieldId { get; set; }
public String NameNative { get; set; }
public String NameEnglish { get; set; }
public Byte[] Logo { get; set; }
public DateTime CreateDate { get; set; }
public virtual User Owner { get; set; }//It is Forign key with user table
}
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public String UserName { get; set; }
public String LoweredUserName { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String LoweredEmail { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String PasswordQuestion { get; set; }
public String PasswordAnswer { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLocked { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime CreateDate { get; set; }
public virtual Business Bussines { get; set; }
}
when I want to add information:
user.Business = new Business
{
OwnerId = user.UserId,
LegalTypeId = business.LegalTypeId,
BusinessTypeId = business.BusinessTypeId,
MainIndustryFieldId = business.MainIndustryFieldId,
NameNative = business.NameNative,
NameEnglish = business.NameEnglish,
Logo = business.Logo,
CreateDate = DateTime.Now
};
ctx.SaveChanges();
I get the following error:
Cannot insert explicit value for identity column in table 'Business'
when IDENTITY_INSERT is set to OFF.
In database column identity specification business chose is Identity Yes.
Somebody can tell what to do.
Can you make sure that in your EDMX model, your BusinessId is set to be handled by the database (property StoreGeneratedPattern = Identity)?? Also: why is your primary key nullable (long?) - makes no sense whatsoever. Your primary key must never be null !
BusinessId can not be empty/null since you have not specified that it should be autogenerated by Sql Server (which Identity means).
Since you are using Code First to generate your database, just change to:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long? BusinessId { get; set; }
override OnModelCreating in DbContext and add in it following Fluent API:
modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);

Resources