I need to map a nullable int to a nullable int via autompper
This my class Incident:
public class Incident : Evenement
{
public Incident()
: base(-1, Global.EvenementType.Incidents, DateTime.MinValue)
{
}
public Incident(int id, DateTime date, string libelle, int formulaireId, string societe, string userName)
: base(id, (int)Global.EvenementType.Incidents, date, libelle, "", "", societe)
{
ContratId = formulaireId;
Contrat = null;
UserName = userName;
}
public Incident(int id, DateTime date, string libelle, string societe, string userName)
: base(id, (int)Global.EvenementType.Incidents, date, libelle, "", "", societe)
{
ContratId = null;
Contrat = null;
UserName = userName;
}
[DataMember]
public int? ContratId { get; set; }
[DataMember]
public Contrat Contrat { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public bool IsGeneral
and this is my class INCIDENT
public partial class INCIDENT : EVENEMENT
{
public Nullable<int> FORMULAIRE_ID { get; set; }
public virtual FORMULAIRE FORMULAIRE { get; set; }
public string USERNAME { get; set; }
}
When I'm doing a mapping and i have a null in contratId dans incident, it's automotically converted to 0 in FORMULAIRE_ID in class INCIDENT
This my bindings
Mapper.CreateMap<Incident, INCIDENT>()
.ForMember(degivreuse => degivreuse.FORMULAIRE_ID, expression => expression.MapFrom(degivreuse => degivreuse.ContratId))
.ForMember(degivreuse => degivreuse.FORMULAIRE, expression => expression.Ignore());
And in the PJ the problem:
Do you have any idea why i don't obtain a null value please?
Regards
I'm not seeing any issues with the way Automapper handles int?. Here's a quick sample that works fine:
public class Src1
{
public string Name { get; set; }
public int? Age { get; set; }
}
public class Dest1
{
public string Name { get; set; }
public Nullable<int> Age { get; set; }
}
Mapper.CreateMap<Src1, Dest1>();
Mapper.AssertConfigurationIsValid();
var s = new Src1 {Name = "aaa", Age = null};
var d = Mapper.Map<Src1, Dest1>(s);
In the sample above, d.Age is null. Can you provide some sample code that reproduces the issue you're seeing?
Today I've stumbled upon the same problem with AutoMapper 10.1.1.
I tried to map my custom class to MarginSettings class in DinkToPdf library.
The MarginSettings class had 2 constructors:
public class MarginSettings
{
public Unit Unit { get; set; }
public double? Top { get; set; }
public double? Bottom { get; set; }
public double? Left { get; set; }
public double? Right { get; set; }
public MarginSettings()
{
Unit = Unit.Millimeters;
}
public MarginSettings(double top, double right, double bottom, double left) : this()
{
Top = top;
Bottom = bottom;
Left = left;
Right = right;
}
// the rest of class..
}
It looks like for some reason AutoMapper is calling a constructor with parameters in MarginSettings class when it tries to map my custom class to it. This way, the default double value (0) is set to double? properties in this constructor.
Here is the code demonstrating this problem:
class SourceClass
{
public double? Top { get; set; }
public double? Bottom { get; set; }
public double? Left { get; set; }
public double? Right { get; set; }
}
class ClassWithoutCtor
{
public double? Top { get; set; }
public double? Bottom { get; set; }
public double? Left { get; set; }
public double? Right { get; set; }
}
// The class similar to one in DinkToPdf library
class ClassWithCtor
{
public string Message1 { get; set; }
public string Message2 { get; set; }
public double? Top { get; set; }
public double? Bottom { get; set; }
public double? Left { get; set; }
public double? Right { get; set; }
public ClassWithCtor() => this.Message1 = "in default ctor";
public ClassWithCtor(double top, double right, double bottom, double left)
: this()
{
this.Top = new double?(top);
this.Bottom = new double?(bottom);
this.Left = new double?(left);
this.Right = new double?(right);
Message2 = "in ctor with parameters";
}
}
class AutoMapperTest
{
public void TryMapZeros()
{
var source = new SourceClass
{
Top = 5,
Bottom = 5
};
var mapConfiguration = new MapperConfiguration(
cfg =>
{
cfg.CreateMap<SourceClass, ClassWithoutCtor>();
cfg.CreateMap<SourceClass, ClassWithCtor>();
}
);
var mapper = mapConfiguration.CreateMapper();
var margin1 = mapper.Map<SourceClass, ClassWithoutCtor>(source);
var margin2 = mapper.Map<SourceClass, ClassWithCtor>(source);
}
}
The mapped objects look this way after the code execution:
margin1
{PdfGeneratorTest.ClassWithoutCtor}
Bottom: 5
Left: null
Right: null
Top: 5
margin2
{PdfGeneratorTest.ClassWithCtor}
Bottom: 5
Left: 0
Message1: "in default ctor"
Message2: "in ctor with parameters"
Right: 0
Top: 5
Related
I'm sure someone has tried to do something like this before, but I'm unsure if what I'm finding in my searches fits what I'm trying to do.
In my .Net 6 Web API I have a class to get data passed by the request:
public abstract class QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
public string Fields { get; set; }
}
For each controller I create a view model which inherits from this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
This works fine when calling an endpoint expecting multiple results and single results. However, I want to split the QueryStringParameters properties that are for pagination, something like this:
public abstract class QueryStringParameters {
public string Fields { get; set; }
}
public abstract class QueryStringParametersPaginated : QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
}
The problem is that then my view modal looks like this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
}
}
public class ProgramParametersPaginated : QueryStringParametersPaginated {
public bool MapDepartment { get; set; } = true; // repeated
public bool MapAnother1 { get; set; } = true; // repeated
public bool MapAnother2 { get; set; } = true; // repeated
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
How can I rewrite this so that ProgramParameters and ProgramParametersPaginated don't have to have the same properties (MapDepartment, MapAnother1, MapAnother2) defined in both?
I tried something like this but that's not allowed and I am unsure how to proceed.
public class ProgramParametersPaginated : ProgramParameters, QueryStringParametersPaginated {
public ProgramParametersPaginated() {
// Default OrderBy
OrderBy = "Id";
}
}
If I understood correctly, you need to extract interfaces instead of using classes as you did, so you can apply multiple implementation.
First define the interfaces and constants for you filter properties:
public enum Constants
{
DefaultPageSizeMax = 500,
DefaultPageSize = 100
}
public interface IQueryStringParameters
{
string Fields { get; set; }
}
public interface IQueryStringParametersPaginated : IQueryStringParameters
{
string OrderBy { get; set; }
int PageSize { get; set; }
int MaxPageSize { get; set; }
int? PageNumber { get; set; }
}
Then you create an abstract class that inherit from both interfaces defined so you can write some behaviour like you did with the setters and getters:
public abstract class BaseProgramParameters : IQueryStringParameters, IQueryStringParametersPaginated
{
public string Fields { get; set; }
public string OrderBy { get; set; }
private int _pageSize = (int)Constants.DefaultPageSize;
private int _maxPageSize = (int)Constants.DefaultPageSizeMax;
public int PageSize
{
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value;
}
public int MaxPageSize { get; set; }
public int? PageNumber { get; set; }
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
public BaseProgramParameters()
{
}
public BaseProgramParameters(string orderBy)
{
this.OrderBy = orderBy;
}
}
Since you may want to define a different value on MapDeparment, MapAnother, etc, you can use the constructor on the child classes:
public class ProgramParametersPaginated : BaseProgramParameters
{
public ProgramParametersPaginated() : base("Id")
{
}
}
public class ProgramParameters : BaseProgramParameters
{
public ProgramParameters()
{
this.MapAnother1 = false;
}
}
Let me know if you have any further doubts.
I am trying to bind a model in a post action method. i.e binding with the help of [Bind] attribute.
Where I post some fields for parent while a collection of child properties at the same time.
Supose I have parent as following
class Parent
{
int field0;
string field1;
string field2;
ICollection<Child> Children;
}
class Child
{
int field3;
string field4;
string field5;
}
at the time of binding I can choose fields to bind for simple binding like [Bind("field1, field2")] and to include children as well then [Bind("field1,field2,children")]
But I need to include some fields of children like children("field4", "field5")
Is there any possibility so that I can write like following
public IActionResult UTOneFlight([Bind("field1, field2, children(field4, field5)")] Parent p)
{
}
UPDATE
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UTOneFlight([Bind("FlightID, SrcAirportID, DestAirportID, FlightDate, Sector, RegistrationNo, FlightNo, CallSign, CrewMembers, EmbDetails, UpdateRemarks")] FlightViewModel f)
{
if (f != null && f.EmbDetails != null)
{
if (f.FlightID == 0)
{
var flight = new Flight()
{
EmbDetails = new List<EmbDetail>(),
FlightType = "emb",
AirlineOperatorID = _user.OperatorID,
SrcAirportID = f.SrcAirportID,
DestAirportID = f.DestAirportID,
FlightDate = f.FlightDate,
Sector = f.Sector.ToString().ToLower()[0],
FlightNo = f.FlightNo.Trim().ToLower(),
CallSign = f.CallSign.Trim().ToLower(),
RegistrationNo = f.RegistrationNo.Trim().ToLower(),
CrewMembers = f.CrewMembers,
UpdateRemarks = f.UpdateRemarks?? f.UpdateRemarks,
EmbDataStatus = 'u',
CreatedBy = _user.UserID
};
foreach (var e in f.EmbDetails)
{
flight.EmbDetails.Add(
new EmbDetail()
{
PaxType = e.PaxType,
PaxClass = e.PaxClass,
AdultPax = e.AdultPax,
Infants = e.Infants,
Dips = e.Dips,
FOC = e.FOC,
TransferPax = e.TransferPax,
CreatedBy = _user.UserID
}
);
}
await _db.AddAsync(flight);
return RedirectToAction("Index");
}
else
{
//var flight = await _db.SingleAsync<Flight>(x => x.FlightID == f.FlightID);
//return RedirectToAction("Index");
}
}
else
return NotFound();
}
and my models are
public class FlightViewModel
{
public long FlightID { get; set; }
public int SrcAirportID { get; set; }
public int DestAirportID { get; set; }
public string RegistrationNo { get; set; }
public string FlightNo { get; set; }
public string CallSign { get; set; }
public DateTime FlightDate { get; set; }
public int CrewMembers { get; set; }
public char Sector { get; set; }
public string UpdateRemarks { get; set; }
public ICollection<EmbDetViewModel> EmbDetails { get; set; }
}
and
public class EmbDetViewModel
{
public string PaxType { get; set; }
public char PaxClass { get; set; }
public int AdultPax { get; set; }
public int Infants { get; set; }
public int Dips { get; set; }
public int Crew { get; set; }
public int FOC { get; set; }
public int TransferPax { get; set; }
}
I need to write signature of the method like
public async Task<IActionResult> UTOneFlight([Bind("FlightID, SrcAirportID, DestAirportID, FlightDate, Sector, RegistrationNo, FlightNo, CallSign, CrewMembers, EmbDetails(PaxType, PaxClass), UpdateRemarks")] FlightViewModel f)
Please have a look at
EmbDetails(PaxType, PaxClass)
How do you send your request body? I test in my side and here's the result.
My model:
public class ParentTestModel
{
public int id { get; set; }
public ICollection<TestModel> testModels { get; set; }
}
public class TestModel
{
public string prefix { get; set; }
}
==============================Update=============================
I test in my side with [JsonIgnore] and the property which added this annotation will be ignored and this is suitable when the request body is a json object like the screenshot above. And if you are sending the request in form-data then you can use [Bind] annotation, I think you may have referred to this document.
I have a class that looks like this
class FeaturedListing
{
public string Title { get; set; }
public string Link { get; set; }
public string Published { get; set; }
public string Views { get; set; }
public string Featured { get; set; }
public string CategoryName { get; set; }
}
And then I have a list that looks like this
public static List<FeaturedListing> FeatiredListingsList = new List<FeaturedListing>();
After adding a few objects to that list, how do I properly sort by Views
views looks like this
0 visits
52 visits
5 visits
etc.
Simplest way is to do an OrderBy on your FeaturedListing.Views.
var orderedList = FeatiredListingsList.OrderBy(x => x.Views).ToList();
However, if you're at liberty to change the structure of your program, you should really consider making Views an int so you can do proper numerical sorting. If you must, for some reason, output the value of Views as 0 visits, 52 visits etc, a better approach is to create a get only property in your FeaturedListing class like this:
public class FeaturedListing
{
public string Title { get; set; }
public string Link { get; set; }
public string Published { get; set; }
public int Views { get; set; }
public string ViewsStr { get { return string.Format("{0} visits", Views); } }
public string Featured { get; set; }
public string CategoryName { get; set; }
}
Use the List.Sort - Sorts the elements in the entire List using the specified System.Comparison..
void Main()
{
var reatiredListingsList = new List<FeaturedListing>();
reatiredListingsList.Add(new FeaturedListing{ Views = "0 Views"});
reatiredListingsList.Add(new FeaturedListing{ Views = "52 Views"});
reatiredListingsList.Add(new FeaturedListing{ Views = "5 Views"});
reatiredListingsList.Sort((x, y) => {
var xv = int.Parse(x.Views.Replace(" Views", ""));
var yv = int.Parse(y.Views.Replace(" Views", ""));
return xv < yv ? -1 : (xv > yv ? 1 : 0);
});
}
class FeaturedListing
{
public string Title { get; set; }
public string Link { get; set; }
public string Published { get; set; }
public string Views { get; set; }
public string Featured { get; set; }
public string CategoryName { get; set; }
}
I've got a problem regarding Json.NET and the omdbapi. I'm trying to retrieve information from the omdbapi and some properties are giving me headaches, particularly the "imdbVotes" one since it's written, in example, as "321,364" so I can't get an integer from it.
I'm betting that I need a custom converter, but I'm afraid that, at the moment, I don't really understand how to create one for my particular problem.
All other properties work well (I'm not using all of them at the moment).
This is the response for, lets say Snatch : http://www.omdbapi.com/?i=&t=snatch
This is my class :
public class MovieJSON
{
[JsonProperty(PropertyName = "Title")]
public String Title { get; set; }
[JsonProperty(PropertyName = "Year")]
public int Year { get; set; }
[JsonProperty(PropertyName = "Genre")]
public String Genre { get; set; }
[JsonProperty(PropertyName = "Director")]
public String Director { get; set; }
[JsonProperty(PropertyName = "Actors")]
public String Actors { get; set; }
[JsonProperty(PropertyName = "Plot")]
public String Plot { get; set; }
[JsonProperty(PropertyName = "Poster")]
public String Poster { get; set; }
[JsonProperty(PropertyName = "Metascore")]
public int Metascore { get; set; }
[JsonProperty(PropertyName = "imdbRating")]
public decimal ImdbRating { get; set; }
[JsonProperty(PropertyName = "imdbVotes")]
public int ImdbVotes { get; set; }
}
UPDATE #1 :
How can I handle the response when the property has the value "N/A"?. That happens for some movies (ie. http://www.omdbapi.com/?i=&t=four+rooms has it's Metascore set to N/A).
UPDATE #2 :
Another related inquiry. I'm using EF6 with MySQL and the idea's to populate the database with movies created through JSON parsing.
This is my Movie class :
[JsonObject(MemberSerialization.OptIn)]
[Table("movies")]
public class MovieJSON
{
[Key]
public int Id { get; set; }
[JsonProperty(PropertyName = "Title")]
[Column("title")]
public String Title { get; set; }
[JsonProperty(PropertyName = "Year")]
[Column("year")]
public int Year { get; set; }
[JsonProperty(PropertyName = "Genre")]
[Column("genre")]
public String Genre { get; set; }
[JsonProperty(PropertyName = "Director")]
[Column("director")]
public String Director { get; set; }
[JsonProperty(PropertyName = "Actors")]
[Column("actors")]
public String Actors { get; set; }
[JsonProperty(PropertyName = "Plot")]
[Column("plot")]
public String Plot { get; set; }
[JsonProperty(PropertyName = "Poster")]
[Column("poster")]
public String Poster { get; set; }
[JsonProperty(PropertyName = "Metascore")]
public String Metascore { get; set; }
[Column("metascore")]
public int MetascoreInt
{
get
{
int result;
if (int.TryParse(Metascore, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result))
return result;
return 0;
}
}
[JsonProperty(PropertyName = "imdbRating")]
public String ImdbRating { get; set; }
[Column("imdb_rating")]
public Decimal ImdbRatingDecimal
{
get
{
Decimal result;
if (Decimal.TryParse(ImdbRating, out result))
return result;
return 0;
}
}
[JsonProperty(PropertyName = "imdbVotes")]
public String ImdbVotes { get; set; }
[Column("imdb_votes")]
public long ImdbVotesLong
{
get
{
long result;
String stringToParse = ImdbVotes.Remove(ImdbVotes.IndexOf(','), 1);
if (long.TryParse(stringToParse, out result))
return result;
return 0;
}
}
[JsonProperty(PropertyName = "imdbID")]
[Column("imdb_id")]
public String ImdbID { get; set; }
[JsonProperty(PropertyName = "type")]
[Column("type")]
public String Type { get; set; }
public override string ToString()
{
String[] propertiesToIgnore = {"MetascoreInt", "ImdbRatingDecimal", "ImdbVotesLong"};
var sb = new StringBuilder();
PropertyInfo[] properties = GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
if (propertiesToIgnore.Contains(propertyInfo.Name))
continue;
sb.AppendLine(String.Format("{0} : {1} ",
propertyInfo.Name, propertyInfo.GetValue(this, null)));
}
return sb.ToString();
}
}
This is my EF6 configuration-context class (I'm ignoring the String fields and instead, using the Helper ones since the database is configured to accept int for Metascore and so on) :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MovieJSON>().Ignore(e => e.Metascore).Ignore(e => e.ImdbRating).Ignore(e => e.ImdbVotes);
base.OnModelCreating(modelBuilder);
}
Additional image info :
Object values before insertion into the database (all values are properly set)
Valid XHTML http://imagizer.imageshack.us/v2/800x600q90/689/8x5m.png
Values in the database :
Valid XHTML http://imagizer.imageshack.us/v2/800x600q90/844/nvc5.png
The helper fields (MetascoreInt, ImdbRatingDecimal, ImdbVotesLong) are returning zero, I can't figure out why.
Any help would be mucho appreciated! :)
All the best
You could have two properties: one would be the string property as it comes from IMDB, and the other would be the int property that converts the string one. To convert, you can use the nifty NumberStyles.AllowThousands flag. So you would have
[JsonProperty(PropertyName = "imdbVotes")]
public string ImdbVotes { get; set; }
public int ImdbVotesInt
{
get
{
int result;
if (int.TryParse(ImdbVotes,
NumberStyles.AllowThousands,
CultureInfo.InvariantCulture,
out result))
return result; // parse is successful, use 'result'
else
return 0; // parse is unsuccessful, return whatever default value works for you
}
}
I have been searching for days now trying to figure this one out. It saves my records correctly but throws the following error:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Unable to set field/property Actors on entity type BOR.DataModel.StagComplaint. See InnerException for details.
I am using Code First and EF 5 in a C# Web Forms solution with a supporting WCF Service. Here are my POCO classes:
public partial class StagComplaint : ComplaintBase {
public IList<StagParcel> Parcels { get; set; }
public IList<StagActor> Actors { get; set; }
public IList<StagRectification> Rectifications { get; set; }
public ComplaintType ComplaintType { get; set; }
public int ComplaintTypeID { get; set; }
public StagComplaint() {
this.Parcels = new List<StagParcel>();
this.Actors = new List<StagActor>();
this.Rectifications = new List<StagRectification>();
}
}
public class ComplaintBase : BORBase {
public string Number { get; set; }
public int ParentID { get; set; }
public int TaxYear { get; set; }
public string Category { get; set; }
public double BuildingValue { get; set; }
public double LandValue { get; set; }
public double OwnerOpinion { get; set; }
public string Notes { get; set; }
}
public class BORBase {
[Required]
public DateTime CreationDate { get; set; }
public int ID { get; set; }
[MaxLength(25)]
[Required]
public string UserIdentification { get; set; }
}
public partial class StagParcel : ParcelBase {
public virtual StagActor Owner { get; set; }
[ForeignKey("Owner")]
public int OwnerID { get; set; }
public StagAddress Address { get; set; }
[IgnoreDataMember]
public virtual StagComplaint Complaint { get; set; }
public int ComplaintID { get; set; }
public StagParcel() {
this.Address = new StagAddress();
}
}
public class ParcelBase : BORBase {
public string Number { get; set; }
public double BuildingValue { get; set; }
public double LandValue { get; set; }
public double OwnerOpinion { get; set; }
public string LandUseCode { get; set; }
public string NeighborhoodCode { get; set; }
public string TaxDistrict { get; set; }
public string SchoolDistrict { get; set; }
public int SchoolBoardID { get; set; }
}
public partial class StagActor : ActorBase {
public StagAddress Address { get; set; }
public virtual IList<StagEmail> Emails { get; set; }
public virtual IList<StagPhone> Phones { get; set; }
[IgnoreDataMember]
public virtual StagComplaint Complaint { get; set; }
public int ComplaintID { get; set; }
public virtual Role Role { get; set; }
public int RoleID { get; set; }
public StagActor() {
this.Emails = new List<StagEmail>();
this.Phones = new List<StagPhone>();
this.Address = new StagAddress();
}
}
public class ActorBase : BORBase {
public string Name { get; set; }
}
public class StagRectification : BORBase {
public bool Active { get; set; }
public string Notes { get; set; }
public virtual RectificationType RectificationType { get; set; }
public int RectificationTypeID { get; set; }
[IgnoreDataMember]
public virtual StagComplaint Complaint { get; set; }
public int ComplaintID { get; set; }
}
This is the client side code I am using to create the Complaint:
public int AddParcelsToStagingComplaint(List<string> parcelIDs, string userID) {
StagComplaint comp = new StagComplaint();
int Result = 0;
using (BORServiceClient db = new BORServiceClient()) {
comp = new StagComplaint() {
BuildingValue = 111222,
Category = "*",
LandValue = 222333,
Number = "*",
TaxYear = DateTime.Now.Year,
ComplaintTypeID = 1,
UserIdentification = userID,
CreationDate = DateTime.Now,
};
StagAddress ca = new StagAddress() { Line1 = "670 Harvard Blvd", City = "Cleveland", State = "OH", ZipCode = "44113", };
List<StagPhone> ps = new List<StagPhone>();
ps.Add(new StagPhone() { Number = "5556664646", Type = PhoneTypes.Home, UserIdentification = userID, CreationDate = DateTime.Now, });
comp.Actors.Add(
new StagActor() {
Name = "Joe Schmoe",
Address = ca,
Phones = ps,
RoleID = 1,
UserIdentification = userID,
CreationDate = DateTime.Now,
}
);
StagAddress aa = new StagAddress() {
City = wp.Address.City,
Line1 = wp.Address.Line1,
Line2 = wp.Address.Line2,
State = wp.Address.State,
ZipCode = wp.Address.ZipCode,
};
ps = new List<StagPhone>();
ps.Add(new StagPhone() { Number = "4448887878", Type = PhoneTypes.Work, UserIdentification = userID, CreationDate = DateTime.Now, });
StagParcel p = new StagParcel() {
Address = new StagAddress() { Line1 = "4 Oxford Drive", City = "Hudson", State = "OH", ZipCode = "44236" },
BuildingValue = wp.BuildingValue,
LandUseCode = wp.LandUseCode,
LandValue = wp.LandValue,
NeighborhoodCode = wp.NeighborhoodCode,
Number = wp.Number,
Owner = new StagActor() { Name = "Owner Person", Address = aa, RoleID = 2, Phones = ps, UserIdentification = userID, CreationDate = DateTime.Now, },
OwnerOpinion = wp.OwnerOpinion,
SchoolBoardID = wp.SchoolBoardID,
SchoolDistrict = wp.SchoolDistrict,
TaxDistrict = wp.TaxDistrict,
UserIdentification = userID,
CreationDate = DateTime.Now,
};
comp.Parcels.Add(p);
ServiceResponse<int> saved = db.AddComplaint((ComplaintBase)comp, Contexts.Staging, userID);
if (saved.WasSuccessful)
Result = saved.Result;
} // using the database
return Result;
} // AddParcelsToStagingComplaint - Method
Here is the WCF method that gets called:
using (StagComplaintRepo cr = new StagComplaintRepo()) {
cr.Add((StagComplaint)complaint, userID);
if (cr.Save()) {
Result.Result = complaint.ID;
Result.WasSuccessful = true;
} else {
Result.AddException(string.Format("Unable to create a new Complaint in the {0} context.", context));
} // if the save was successful
} // using the Complaint Repository
And here is the BaseRepository that has the Save and Add methods:
public abstract class BaseRepository<T> : IDisposable, IRepository<T> where T : class {
public virtual bool Save(bool detectChanges = false) {
if (detectChanges == true)
this.Entities.ChangeTracker.DetectChanges();
return (this.Entities.SaveChanges() > 0);
}
public virtual void Add(T entity, string userID) {
this.Entities.Set<T>().Add(entity);
}
...
}
It fails on the above this.Entities.SaveChanges() call with the error mentioned at the top of this post. There is no extra inner exception. If I only fill in the Complaint properties that are required and are part of that object, it works. But once I add a Parcel with an Actor it fails.
I assume it is something simple, perhaps a switch needs to be turned on or off. But similar errors all seem to reference AcceptChanges and that is not the issue here. At least based on the error message. Any help would be appreciated.
EDIT
Here is the full stack trace:
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at BOR.WebService.Repositories.BaseRepository`1.Save(Boolean detectChanges) in d:\DevProjects\BOR\WebService\Main\Source\WebServiceSolution\WcfServiceProject\Repositories\BaseRepository.cs:line 22
at BOR.WebService.BORService.AddComplaint(ComplaintBase complaint, Contexts context, String userID) in d:\DevProjects\BOR\WebService\Main\Source\WebServiceSolution\WcfServiceProject\BORService.svc.cs:line 65
Line 22 is:
return (this.Entities.SaveChanges() > 0);
Line 65 is:
if (cr.Save()) {