This is my code :
http://i43.tinypic.com/acpgdd.jpg
entities = new SamaEntities();
var institute_ContractInstitute = entities.ContractInstitutes;
I get this error in watch page
institute_ContractInstitute The name 'institute_ContractInstitute'
does not exist in the current context
What does it mean?
This is ContractInstitute Class :
public partial class ContractInstitute : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new ContractInstitute object.
/// </summary>
/// <param name="id">Initial value of the Id property.</param>
/// <param name="contractId">Initial value of the ContractId property.</param>
/// <param name="instituteId">Initial value of the InstituteId property.</param>
/// <param name="status">Initial value of the Status property.</param>
/// <param name="level">Initial value of the Level property.</param>
/// <param name="user_">Initial value of the User_ property.</param>
public static ContractInstitute CreateContractInstitute(global::System.Int32 id, global::System.Int32 contractId, global::System.Int32 instituteId, global::System.Int16 status, global::System.Int16 level, global::System.Int32 user_)
{
ContractInstitute contractInstitute = new ContractInstitute();
contractInstitute.Id = id;
contractInstitute.ContractId = contractId;
contractInstitute.InstituteId = instituteId;
contractInstitute.Status = status;
contractInstitute.Level = level;
contractInstitute.User_ = user_;
return contractInstitute;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Id
{
get
{
return _Id;
}
set
{
if (_Id != value)
{
OnIdChanging(value);
ReportPropertyChanging("Id");
_Id = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Id");
OnIdChanged();
}
}
}
private global::System.Int32 _Id;
partial void OnIdChanging(global::System.Int32 value);
partial void OnIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> Price
{
get
{
return _Price;
}
set
{
OnPriceChanging(value);
ReportPropertyChanging("Price");
_Price = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Price");
OnPriceChanged();
}
}
private Nullable<global::System.Double> _Price;
partial void OnPriceChanging(Nullable<global::System.Double> value);
partial void OnPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ContractId
{
get
{
return _ContractId;
}
set
{
OnContractIdChanging(value);
ReportPropertyChanging("ContractId");
_ContractId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ContractId");
OnContractIdChanged();
}
}
private global::System.Int32 _ContractId;
partial void OnContractIdChanging(global::System.Int32 value);
partial void OnContractIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 InstituteId
{
get
{
return _InstituteId;
}
set
{
OnInstituteIdChanging(value);
ReportPropertyChanging("InstituteId");
_InstituteId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("InstituteId");
OnInstituteIdChanged();
}
}
private global::System.Int32 _InstituteId;
partial void OnInstituteIdChanging(global::System.Int32 value);
partial void OnInstituteIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int16 Status
{
get
{
return _Status;
}
set
{
OnStatusChanging(value);
ReportPropertyChanging("Status");
_Status = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Status");
OnStatusChanged();
}
}
private global::System.Int16 _Status;
partial void OnStatusChanging(global::System.Int16 value);
partial void OnStatusChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> CouncilPrice
{
get
{
return _CouncilPrice;
}
set
{
OnCouncilPriceChanging(value);
ReportPropertyChanging("CouncilPrice");
_CouncilPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CouncilPrice");
OnCouncilPriceChanged();
}
}
private Nullable<global::System.Double> _CouncilPrice;
partial void OnCouncilPriceChanging(Nullable<global::System.Double> value);
partial void OnCouncilPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> CurrencyId
{
get
{
return _CurrencyId;
}
set
{
OnCurrencyIdChanging(value);
ReportPropertyChanging("CurrencyId");
_CurrencyId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CurrencyId");
OnCurrencyIdChanged();
}
}
private Nullable<global::System.Int32> _CurrencyId;
partial void OnCurrencyIdChanging(Nullable<global::System.Int32> value);
partial void OnCurrencyIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int16 Level
{
get
{
return _Level;
}
set
{
OnLevelChanging(value);
ReportPropertyChanging("Level");
_Level = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Level");
OnLevelChanged();
}
}
private global::System.Int16 _Level;
partial void OnLevelChanging(global::System.Int16 value);
partial void OnLevelChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 User_
{
get
{
return _User_;
}
set
{
OnUser_Changing(value);
ReportPropertyChanging("User_");
_User_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("User_");
OnUser_Changed();
}
}
private global::System.Int32 _User_;
partial void OnUser_Changing(global::System.Int32 value);
partial void OnUser_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> UserDelegate_
{
get
{
return _UserDelegate_;
}
set
{
OnUserDelegate_Changing(value);
ReportPropertyChanging("UserDelegate_");
_UserDelegate_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserDelegate_");
OnUserDelegate_Changed();
}
}
private Nullable<global::System.Int32> _UserDelegate_;
partial void OnUserDelegate_Changing(Nullable<global::System.Int32> value);
partial void OnUserDelegate_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> UserLoginAz_
{
get
{
return _UserLoginAz_;
}
set
{
OnUserLoginAz_Changing(value);
ReportPropertyChanging("UserLoginAz_");
_UserLoginAz_ = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserLoginAz_");
OnUserLoginAz_Changed();
}
}
private Nullable<global::System.Int32> _UserLoginAz_;
partial void OnUserLoginAz_Changing(Nullable<global::System.Int32> value);
partial void OnUserLoginAz_Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> HoldingPrice
{
get
{
return _HoldingPrice;
}
set
{
OnHoldingPriceChanging(value);
ReportPropertyChanging("HoldingPrice");
_HoldingPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("HoldingPrice");
OnHoldingPriceChanged();
}
}
private Nullable<global::System.Double> _HoldingPrice;
partial void OnHoldingPriceChanging(Nullable<global::System.Double> value);
partial void OnHoldingPriceChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Double> CouncilHoldingPrice
{
get
{
return _CouncilHoldingPrice;
}
set
{
OnCouncilHoldingPriceChanging(value);
ReportPropertyChanging("CouncilHoldingPrice");
_CouncilHoldingPrice = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CouncilHoldingPrice");
OnCouncilHoldingPriceChanged();
}
}
private Nullable<global::System.Double> _CouncilHoldingPrice;
partial void OnCouncilHoldingPriceChanging(Nullable<global::System.Double> value);
partial void OnCouncilHoldingPriceChanged();
#endregion
#region Navigation Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "ConInsGroup", "Group")]
public EntityCollection<Group> Groups
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Group>("SamaModel.ConInsGroup", "Group");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Group>("SamaModel.ConInsGroup", "Group", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "ContractContractInstitute", "Contract")]
public Contract Contract
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Contract> ContractReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Contract>("SamaModel.ContractContractInstitute", "Contract", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "InstituteContractInstitute", "Institute")]
public Institute Institute
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Institute> InstituteReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Institute>("SamaModel.InstituteContractInstitute", "Institute", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("SamaModel", "CurrencyContractInstitute", "Currency")]
public Currency Currency
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<Currency> CurrencyReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Currency>("SamaModel.CurrencyContractInstitute", "Currency", value);
}
}
}
#endregion
}
I get this error in watch page
The name 'institute_ContractInstitute' does not exist in the current context
That means exactly what it says: no variable with the name institute_ContractInstitute exists in the current context, i.e. where your program currently is.
Put a breakpoint after var institute_ContractInstitute = ... and then you can inspect its contents in the Watch window.
Probably the issue is due to lazy loading. whatever data is in entities.ContractInstitutes is not getting loaded. Try to use a List<> type variable and put the ContractInstitutes into the list using .ToList().
Related
As far as I know, protobuf-net starting from v2 supports references but they cannot be used in conjunction with surrogate (exception "A reference-tracked object changed reference during deserialization" is thrown in this case)
I'm wondering if there is some workaround that I didn't consider to make it works.
Here following the code of my test case that reproduces the above exception.
Classes
public class Person
{
public Person(string name, GenderType gender)
{
Name = name;
Gender = gender;
}
public string Name { get; set; }
public GenderType Gender { get; set; }
}
[Flags]
public enum GenderType : byte
{
Male = 1,
Female = 2,
Both = Male | Female
}
public class Family
{
public Family(List<Person> people, Person familyHead = null)
{
People = people;
FamilyHead = familyHead;
}
public List<Person> People { get; set; }
public Person FamilyHead { get; set; }
}
public class PersonSurrogate
{
public string Name { get; set; }
public byte Gender { get; set; }
public PersonSurrogate(string name, byte gender)
{
Name = name;
Gender = gender;
}
#region Static Methods
public static implicit operator Person(PersonSurrogate surrogate)
{
if (surrogate == null) return null;
return new Person(surrogate.Name, (GenderType)surrogate.Gender);
}
public static implicit operator PersonSurrogate(Person source)
{
return source == null ? null : new PersonSurrogate(source.Name, (byte)source.Gender);
}
#endregion
}
public class FamilySurrogate
{
public FamilySurrogate(List<Person> people, Person familyHead)
{
People = people;
FamilyHead = familyHead;
}
public List<Person> People { get; set; }
public Person FamilyHead { get; set; }
#region Static Methods
public static implicit operator Family(FamilySurrogate surrogate)
{
if (surrogate == null) return null;
return new Family(surrogate.People, surrogate.FamilyHead);
}
public static implicit operator FamilySurrogate(Family source)
{
return source == null ? null : new FamilySurrogate(source.People, source.FamilyHead);
}
#endregion
}
Serializer
/// <summary>
/// Class with model for protobuf serialization
/// </summary>
public class FamilySerializer
{
public GenderType GenderToInclude;
public FamilySerializer(Family family, GenderType genderToInclude = GenderType.Both)
{
GenderToInclude = genderToInclude;
Family = family;
Init();
}
private void Init()
{
Model = RuntimeTypeModel.Create();
FillModel();
Model.CompileInPlace();
}
public FamilySerializer()
{
Init();
}
public Family Family { get; set; }
public RuntimeTypeModel Model { get; protected set; }
protected virtual void FillModel()
{
Model = RuntimeTypeModel.Create();
Model.Add(typeof(Family), false)
.SetSurrogate(typeof(FamilySurrogate));
MetaType mt = Model[typeof(FamilySurrogate)];
mt.Add(1, "People");
mt.AddField(2, "FamilyHead").AsReference = true; // Exception "A reference-tracked object changed reference during deserialization" - because using surrogate.
mt.UseConstructor = false;
Model.Add(typeof(Person), false)
.SetSurrogate(typeof(PersonSurrogate));
mt = Model[typeof(PersonSurrogate)]
.Add(1, "Name")
.Add(2, "Gender");
mt.UseConstructor = false; // Avoids to use the parameterless constructor.
}
public void Save(string fileName)
{
using (Stream s = File.Open(fileName, FileMode.Create, FileAccess.Write))
{
Model.Serialize(s, Family, new ProtoBuf.SerializationContext(){Context = this});
}
}
public void Open(string fileName)
{
using (Stream s = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
Family = (Family)Model.Deserialize(s, null, typeof(Family), new ProtoBuf.SerializationContext(){Context = this});
}
}
}
Test Case
private Family FamilyTestCase(string fileName, bool save)
{
if (save)
{
var people = new List<Person>()
{
new Person("Angus", GenderType.Male),
new Person("John", GenderType.Male),
new Person("Katrina", GenderType.Female),
};
var fam = new Family(people, people[0]);
var famSer = new FamilySerializer(fam);
famSer.Save(fileName);
return fam;
}
else
{
var famSer = new FamilySerializer();
famSer.Open(fileName);
if (Object.ReferenceEquals(fam.People[0], fam.FamilyHead))
{
// I'd like this condition would be satisfied
}
return famSer.Family;
}
}
I think for now this is just an unsupported scenario and I'm unaware of a way to make it magically work; it may be something that I can get back to at some point, but there are many much higher priority things that would take precedence.
My usual advice here - and this applies to any serializer, not just protobuf-net: any time you find yourself hitting a limitation of the serializer, or even just something that is awkward to configure in the serializer: stop fighting the serializer. This kind of problem almost always arises when people try to serialize their regular domain model, and something in the domain model isn't a perfect fit for their chosen serializer. Instead of trying arcane magic: split your model - have your domain model be a good fit for what you want your application to see, and create a separate model that is a great fit for your serializer. Then you don't need concepts like "surrogates". If you're using multiple serialization formats, or have multiple different "versions" of layout in the same serialization format: have multiple serialization models.
It really isn't worth the headache of trying to make on model serve multiple masters.
Since I understand that will be not a supported scenario, I found a way to handle this and I'd like to share my complete solution, in case someone else needs this (or if someone else wanted to share a better solution or improve my approach)
Classes
public class Person
{
public Person(string name, GenderType gender)
{
Name = name;
Gender = gender;
}
public string Name { get; set; }
public GenderType Gender { get; set; }
}
[Flags]
public enum GenderType : byte
{
Male = 1,
Female = 2,
Both = Male | Female
}
public class Family
{
public Family(List<Person> people, Person familyHead = null)
{
People = people;
FamilyHead = familyHead;
}
public List<Person> People { get; set; }
public Person FamilyHead { get; set; }
}
#region Interfaces
/// <summary>
/// Interface for objects supporting the object graph reference.
/// </summary>
public interface ISurrogateWithReferenceId
{
/// <summary>
/// Gets or sets the id for the object referenced more than once during the process of serialization/deserialization.
/// </summary>
/// <remarks>Default value is -1.</remarks>
int ReferenceId { get; set; }
}
#endregion
public class PersonSurrogate : ISurrogateWithReferenceId
{
/// <summary>
/// Standard constructor.
/// </summary>
public PersonSurrogate(string name, byte gender)
{
Name = name;
Gender = gender;
ReferenceId = -1;
}
/// <summary>
/// Private constructor for object graph reference handling.
/// </summary>
private PersonSurrogate(int referenceId)
{
ReferenceId = referenceId;
}
public string Name { get; set; }
public byte Gender { get; set; }
#region object graph reference
/// <summary>
/// Gets the unique id assigned to the surrogate during the process of serialization/deserialization to handle object graph reference.
/// </summary>
/// <remarks>Default value is -1.</remarks>
public int ReferenceId { get; set; }
public override bool Equals(object obj)
{
return base.Equals(obj) || (ReferenceId > 0 && obj is ISurrogateWithReferenceId oi && oi.ReferenceId == ReferenceId);
}
public override int GetHashCode()
{
if (ReferenceId > 0)
return ReferenceId;
return base.GetHashCode();
}
#endregion object graph reference
protected virtual bool CheckSurrogateData(GenderType gender)
{
return gender == GenderType.Both || (GenderType)Gender == gender;
}
#region Static Methods
/// <summary>
/// Converts the surrogate to the related object during the deserialization process.
/// </summary>
public static implicit operator Person(PersonSurrogate surrogate)
{
if (surrogate == null) return null;
if (FamilySerializer.GetCachedObject(surrogate) is Person obj)
return obj;
obj = new Person(surrogate.Name, (GenderType)surrogate.Gender);
FamilySerializer.AddToCache(surrogate, obj);
return obj;
}
/// <summary>
/// Converts the object to the related surrogate during the serialization process.
/// </summary>
public static implicit operator PersonSurrogate(Person source)
{
if (source == null) return null;
if (FamilySerializer.GetCachedObjectWithReferenceId(source) is PersonSurrogate surrogate)
{
surrogate = new PersonSurrogate(surrogate.ReferenceId);
}
else
{
surrogate = new PersonSurrogate(source.Name, (byte)source.Gender);
FamilySerializer.AddToCache(source, surrogate);
}
return surrogate;
}
#endregion
}
public class FamilySurrogate
{
public FamilySurrogate(List<Person> people, Person familyHead)
{
People = people;
FamilyHead = familyHead;
}
public List<Person> People { get; set; }
public Person FamilyHead { get; set; }
#region Static Methods
public static implicit operator Family(FamilySurrogate surrogate)
{
if (surrogate == null) return null;
return new Family(surrogate.People, surrogate.FamilyHead);
}
public static implicit operator FamilySurrogate(Family source)
{
return source == null ? null : new FamilySurrogate(source.People, source.FamilyHead);
}
#endregion
}
Serializer
/// <summary>
/// Class with model for protobuf serialization
/// </summary>
public class FamilySerializer
{
public GenderType GenderToInclude;
public FamilySerializer(Family family, GenderType genderToInclude = GenderType.Both)
{
GenderToInclude = genderToInclude;
Family = family;
Init();
}
private void Init()
{
Model = RuntimeTypeModel.Create();
FillModel();
Model.CompileInPlace();
}
public FamilySerializer()
{
Init();
}
public Family Family { get; set; }
public RuntimeTypeModel Model { get; protected set; }
protected virtual void FillModel()
{
Model = RuntimeTypeModel.Create();
Model.Add(typeof(Family), false)
.SetSurrogate(typeof(FamilySurrogate));
MetaType mt = Model[typeof(FamilySurrogate)];
mt.Add(1, "People"); // This is a list of Person of course
//mt.AddField(2, "FamilyHead").AsReference = true; // Exception "A reference-tracked object changed reference during deserialization" - because using surrogate.
mt.Add(2, "FamilyHead");
mt.UseConstructor = false;
Model.Add(typeof(Person), false)
.SetSurrogate(typeof(PersonSurrogate));
mt = Model[typeof(PersonSurrogate)]
.Add(1, "Name")
.Add(2, "Gender")
.Add(3, "ReferenceId");
mt.UseConstructor = false; // Avoids to use the parameter-less constructor.
}
#region Cache
static FamilySerializer()
{
ResizeCache();
}
/// <summary>
/// Resizes the cache for object graph reference handling.
/// </summary>
/// <param name="size"></param>
public static void ResizeCache(int size = 500)
{
if (_cache != null)
{
foreach (var pair in _cache)
{
pair.Value.ResetCache();
}
}
_cache = new ConcurrentDictionary<int, FamilySerializerCache>();
for (var i = 0; i < size; i++)
_cache.TryAdd(i, new FamilySerializerCache());
}
private static ConcurrentDictionary<int, FamilySerializerCache> _cache;
/// <summary>
/// For internal use only. Adds the specified key and value to the serializer cache for the current thread during the serialization process.
/// </summary>
/// <param name="objKey">The the element to add as key.</param>
/// <param name="objValue">The value of the element to add.</param>
/// <remarks>The <see cref="ISurrogateWithReferenceId.ReferenceId"/> is updated for <see cref="objValue"/></remarks>
public static void AddToCache(object objKey, ISurrogateWithReferenceId objValue)
{
_cache[Thread.CurrentThread.ManagedThreadId].AddToCache(objKey, objValue);
}
/// <summary>
/// For internal use only. Adds the specified key and value to the serializer cache for the current thread during the serialization process.
/// </summary>
/// <param name="objKey">The the element to add as key.</param>
/// <param name="objValue">The value of the element to add.</param>
/// <remarks>The <see cref="ISurrogateWithReferenceId.ReferenceId"/> is updated for <see cref="objKey"/></remarks>
public static void AddToCache(ISurrogateWithReferenceId objKey, object objValue)
{
_cache[Thread.CurrentThread.ManagedThreadId].AddToCache(objKey, objValue);
}
/// <summary>
/// For internal use only. Resets the cache for the current thread.
/// </summary>
public static void ResetCache()
{
_cache[Thread.CurrentThread.ManagedThreadId].ResetCache();
}
/// <summary>
/// For internal use only. Gets the <see cref="ISurrogateWithReferenceId"/> associated with the specified object for the current thread.
/// </summary>
/// <param name="obj">The object corresponding to the value to get.</param>
/// <returns>The related ISurrogateWithReferenceId if presents, otherwise null.</returns>
public static ISurrogateWithReferenceId GetCachedObjectWithReferenceId(object obj)
{
return _cache[Thread.CurrentThread.ManagedThreadId].GetCachedObjectWithReferenceId(obj);
}
/// <summary>
/// For internal use only. Gets the object associated with the specified <see cref="ISurrogateWithReferenceId"/>.
/// </summary>
/// <param name="surrogateWithReferenceId">The <see cref="ISurrogateWithReferenceId"/> corresponding to the object to get.</param>
/// <returns>The related object if presents, otherwise null.</returns>
public static object GetCachedObject(ISurrogateWithReferenceId surrogateWithReferenceId)
{
return _cache[Thread.CurrentThread.ManagedThreadId].GetCachedObject(surrogateWithReferenceId);
}
#endregion Cache
public void Save(string fileName)
{
using (Stream s = File.Open(fileName, FileMode.Create, FileAccess.Write))
{
Model.Serialize(s, Family, new ProtoBuf.SerializationContext(){Context = this});
}
}
public void Open(string fileName)
{
using (Stream s = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
Family = (Family)Model.Deserialize(s, null, typeof(Family), new ProtoBuf.SerializationContext(){Context = this});
}
}
}
Serializer cache
/// <summary>
/// Helper class to support object graph reference
/// </summary>
internal class FamilySerializerCache
{
// weak table for serialization
// ConditionalWeakTable uses ReferenceEquals() rather than GetHashCode() and Equals() methods to do equality checks, so I can use it as a cache during the writing process to overcome the issue with objects that have overridden the GetHashCode() and Equals() methods.
private ConditionalWeakTable<object, ISurrogateWithReferenceId> _writingTable = new ConditionalWeakTable<object, ISurrogateWithReferenceId>();
// dictionary for deserialization
private readonly Dictionary<ISurrogateWithReferenceId, object> _readingDictionary = new Dictionary<ISurrogateWithReferenceId, object>();
private int _referenceIdCounter = 1;
/// <summary>
/// Gets the value associated with the specified key during serialization process.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
/// <returns>True if the internal dictionary contains an element with the specified key, otherwise False.</returns>
private bool TryGetCachedObject(object key, out ISurrogateWithReferenceId value)
{
return _writingTable.TryGetValue(key, out value);
}
/// <summary>
/// Gets the value associated with the specified key during deserialization process.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
/// <returns>True if the internal dictionary contains an element with the specified key, otherwise False.</returns>
private bool TryGetCachedObject(ISurrogateWithReferenceId key, out object value)
{
return _readingDictionary.TryGetValue(key, out value);
}
/// <summary>
/// Resets the internal dictionaries and the counter;
/// </summary>
public void ResetCache()
{
_referenceIdCounter = 1;
_readingDictionary.Clear();
// ConditionalWeakTable automatically removes the key/value entry as soon as no other references to a key exist outside the table, but I want to clean it as well.
_writingTable = new ConditionalWeakTable<object, ISurrogateWithReferenceId>();
}
/// <summary>
/// Adds the specified key and value to the internal dictionary during serialization process.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
/// <remarks>If the object implements <see cref="ISurrogateWithReferenceId"/> interface then <see cref="ISurrogateWithReferenceId.ReferenceId"/> is updated.</remarks>
public void AddToCache(object key, ISurrogateWithReferenceId value)
{
if (value.ReferenceId == -1)
value.ReferenceId = _referenceIdCounter++;
_writingTable.Add(key, value);
}
/// <summary>
/// Adds the specified key and value to the internal dictionary during deserialization process.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
/// <remarks>If the object implements <see cref="ISurrogateWithReferenceId"/> interface then <see cref="ISurrogateWithReferenceId.ReferenceId"/> is updated.</remarks>
public void AddToCache(ISurrogateWithReferenceId key, object value)
{
if (key.ReferenceId == -1)
key.ReferenceId = _referenceIdCounter++;
_readingDictionary.Add(key, value);
}
/// <summary>
/// Gets the <see cref="ISurrogateWithReferenceId"/> associated with the specified object.
/// </summary>
/// <param name="obj">The object corresponding to the value to get.</param>
/// <returns>The related ISurrogateWithReferenceId if presents, otherwise null.</returns>
public ISurrogateWithReferenceId GetCachedObjectWithReferenceId(object obj)
{
if (TryGetCachedObject(obj, out ISurrogateWithReferenceId value))
return value;
return null;
}
/// <summary>
/// Gets the object associated with the specified <see cref="ISurrogateWithReferenceId"/>.
/// </summary>
/// <param name="surrogateWithReferenceId">The <see cref="ISurrogateWithReferenceId"/> corresponding to the object to get.</param>
/// <returns>The related object if presents, otherwise null.</returns>
public object GetCachedObject(ISurrogateWithReferenceId surrogateWithReferenceId)
{
if (TryGetCachedObject(surrogateWithReferenceId, out object value))
return value;
return null;
}
}
Test Case
private Family FamilyTestCase(string fileName, bool save)
{
if (save)
{
var people = new List<Person>()
{
new Person("Angus", GenderType.Male),
new Person("John", GenderType.Male),
new Person("Katrina", GenderType.Female),
};
var fam = new Family(people, people[0]);
var famSer = new FamilySerializer(fam);
famSer.Save(fileName);
return fam;
}
else
{
var famSer = new FamilySerializer();
famSer.Open(fileName);
if (Object.ReferenceEquals(fam.People[0], fam.FamilyHead))
{
Console.WriteLine("Family head is the same than People[0]!");
}
return famSer.Family;
}
}
I'm using ASP.NET Web API Help Page for my web API, but unfortunately controller method's that uses ParameterBindingAttribute are not being listed on GetApiExplorer(). Example bellow GetOutPut is listed and GetEntrance not.
public HelpController() : this(GlobalConfiguration.Configuration) { }
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public ActionResult Index()
{
ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
Controller's methods
/// <summary>
/// Entrance
/// </summary>
/// <param name="foo"></param>
/// <param name="initialDate"></param>
/// <param name="finalDate"></param>
/// <returns></returns>
[Route("entrance/{foo}/{initialDate}/{finalDate}")]
[HttpGet]
[ResponseType(typeof(BooModel))]
public IHttpActionResult GetEntrance(string foo,
[DateTimeParameter(DateFormat = DateTimeBindingFormats.yyyyMMddHHmm)] DateTime? initialDate,
[DateTimeParameter(DateFormat = DateTimeBindingFormats.yyyyMMddHHmm)] DateTime? finalDate)
{
try
{
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
/// <summary>
/// Out Put
/// </summary>
/// <param name="foo"></param>
/// <param name="initialDate"></param>
/// <param name="finalDate"></param>
/// <returns></returns>
[Route("output/{foo}/{initialDate}/{finalDate}")]
[HttpGet]
[ResponseType(typeof(FooModel))]
public IHttpActionResult GetOutPut(string foo, DateTime? initialDate, DateTime? finalDate)
{
try
{
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
XMLDocument.xml
<member name="M:IntegrationServices.Controllers.FooController.GetEntrance(System.String,System.Nullable{System.DateTime},System.Nullable{System.DateTime})">
<summary>
Entrance
</summary>
<param name="foo"></param>
<param name="initialDate"></param>
<param name="finalDate"></param>
<returns></returns>
</member>
<member name="M:IntegrationServices.Controllers.FooController.GetOutPut(System.String,System.Nullable{System.DateTime},System.Nullable{System.DateTime})">
<summary>
Out Put
</summary>
<param name="foo"></param>
<param name="initialDate"></param>
<param name="finalDate"></param>
<returns></returns>
</member>
ParameterBindingAttribute's class
public class DateTimeParameterAttribute : ParameterBindingAttribute
{
public string DateFormat { get; set; }
public bool ReadFromQueryString { get; set; }
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
if (parameter.ParameterType != typeof(DateTime?)) return parameter.BindAsError("Expected type DateTime?");
var binding = new DateTimeParameterBinding(parameter)
{
DateFormat = DateFormat,
ReadFromQueryString = ReadFromQueryString
};
return binding;
}
}
Any ideas?
I have list of Contacts:
public class Contact
{
private string _firstName;
private string _lastName;
private int _age;
/// <summary>
/// Constructor
/// </summary>
/// <param name="fname">Contact's First Name</param>
/// <param name="lname">Contact's Last Name</param>
/// <param name="age">Contact's Age</param>
public Contact(string fname, string lname, int age)
{
_firstName = fname;
_lastName = lname;
_age = age;
}
/// <summary>
/// Contact Last Name
/// </summary>
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
/// <summary>
/// Contact First Name
/// </summary>
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
/// <summary>
/// Contact Age
/// </summary>
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
}
and here I am creating my list:
private List<Contact> _contactList;
_contactList = new List<Contact>();
_contactList.Add(new Contact("John", "Jackson", 45));
_contactList.Add(new Contact("Jack", "Doe", 20));
_contactList.Add(new Contact("Jassy", "Dol", 19));
_contactList.Add(new Contact("Sam", "Josin", 44));
Right now I am trying to get all the first names of all the contacts in separate list using LINQ.
So far I tried:
public List<string> FirstNames
{
get
{
return _contactList.Where(C => C.FirstName.ToList());
}
}
You want to use the Select method, not Where here:
_contactList.Select(C => C.FirstName).ToList();
Further, the need for the ToList() only exists because the property demands it. You could return an IEnumerable<string> instead if you wanted to get rid of that.
public List<string> FirstNames
{
get
{
return _contactList.Select(C => C.FirstName).ToList();
}
}
In my .net (3.5) application with EF I use following code to insert new record, but AddObject() is not working.
I am surprise because it happens first time, even before when I had worked on EF at that time its was working.
My code
public void NewAirline(string name, string sname, string remark)
{
GsecEntities e = new GsecEntities();
tbAirLine al = new tbAirLine()
{
Name = name,
Remark = remark,
ShortName = sname
};
e.tbAirLines.AddObject(al);
e.SaveChanges();
}
As suggestion Here I am writing code of tbAirline
public partial class GsecEntities : global::System.Data.Objects.ObjectContext
{
/// <summary>
/// Initializes a new GsecEntities object using the connection string found in the 'GsecEntities' section of the application configuration file.
/// </summary>
public GsecEntities() :
base("name=GsecEntities", "GsecEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new GsecEntities object.
/// </summary>
public GsecEntities(string connectionString) :
base(connectionString, "GsecEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new GsecEntities object.
/// </summary>
public GsecEntities(global::System.Data.EntityClient.EntityConnection connection) :
base(connection, "GsecEntities")
{
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// There are no comments for tbAirLines in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbAirLine> tbAirLines
{
get
{
if ((this._tbAirLines == null))
{
this._tbAirLines = base.CreateQuery<tbAirLine>("[tbAirLines]");
}
return this._tbAirLines;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbAirLine> _tbAirLines;
/// <summary>
/// There are no comments for tbBanks in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbBank> tbBanks
{
get
{
if ((this._tbBanks == null))
{
this._tbBanks = base.CreateQuery<tbBank>("[tbBanks]");
}
return this._tbBanks;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbBank> _tbBanks;
/// <summary>
/// There are no comments for tbCities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCity> tbCities
{
get
{
if ((this._tbCities == null))
{
this._tbCities = base.CreateQuery<tbCity>("[tbCities]");
}
return this._tbCities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCity> _tbCities;
/// <summary>
/// There are no comments for tbCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCommodity> tbCommodities
{
get
{
if ((this._tbCommodities == null))
{
this._tbCommodities = base.CreateQuery<tbCommodity>("[tbCommodities]");
}
return this._tbCommodities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCommodity> _tbCommodities;
/// <summary>
/// There are no comments for tbCountries in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbCountry> tbCountries
{
get
{
if ((this._tbCountries == null))
{
this._tbCountries = base.CreateQuery<tbCountry>("[tbCountries]");
}
return this._tbCountries;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbCountry> _tbCountries;
/// <summary>
/// There are no comments for tbFlights in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbFlight> tbFlights
{
get
{
if ((this._tbFlights == null))
{
this._tbFlights = base.CreateQuery<tbFlight>("[tbFlights]");
}
return this._tbFlights;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbFlight> _tbFlights;
/// <summary>
/// There are no comments for tbGrpCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbGrpCommodity> tbGrpCommodities
{
get
{
if ((this._tbGrpCommodities == null))
{
this._tbGrpCommodities = base.CreateQuery<tbGrpCommodity>("[tbGrpCommodities]");
}
return this._tbGrpCommodities;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbGrpCommodity> _tbGrpCommodities;
/// <summary>
/// There are no comments for tbPersons in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbPerson> tbPersons
{
get
{
if ((this._tbPersons == null))
{
this._tbPersons = base.CreateQuery<tbPerson>("[tbPersons]");
}
return this._tbPersons;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbPerson> _tbPersons;
/// <summary>
/// There are no comments for tbPersonTypes in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public global::System.Data.Objects.ObjectQuery<tbPersonType> tbPersonTypes
{
get
{
if ((this._tbPersonTypes == null))
{
this._tbPersonTypes = base.CreateQuery<tbPersonType>("[tbPersonTypes]");
}
return this._tbPersonTypes;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<tbPersonType> _tbPersonTypes;
/// <summary>
/// There are no comments for tbAirLines in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbAirLines(tbAirLine tbAirLine)
{
base.AddObject("tbAirLines", tbAirLine);
}
/// <summary>
/// There are no comments for tbBanks in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbBanks(tbBank tbBank)
{
base.AddObject("tbBanks", tbBank);
}
/// <summary>
/// There are no comments for tbCities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCities(tbCity tbCity)
{
base.AddObject("tbCities", tbCity);
}
/// <summary>
/// There are no comments for tbCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCommodities(tbCommodity tbCommodity)
{
base.AddObject("tbCommodities", tbCommodity);
}
/// <summary>
/// There are no comments for tbCountries in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbCountries(tbCountry tbCountry)
{
base.AddObject("tbCountries", tbCountry);
}
/// <summary>
/// There are no comments for tbFlights in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbFlights(tbFlight tbFlight)
{
base.AddObject("tbFlights", tbFlight);
}
/// <summary>
/// There are no comments for tbGrpCommodities in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbGrpCommodities(tbGrpCommodity tbGrpCommodity)
{
base.AddObject("tbGrpCommodities", tbGrpCommodity);
}
/// <summary>
/// There are no comments for tbPersons in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbPersons(tbPerson tbPerson)
{
base.AddObject("tbPersons", tbPerson);
}
/// <summary>
/// There are no comments for tbPersonTypes in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public void AddTotbPersonTypes(tbPersonType tbPersonType)
{
base.AddObject("tbPersonTypes", tbPersonType);
}
}
/// <summary>
/// There are no comments for GsecModel.tbAirLine in the schema.
/// </summary>
/// <KeyProperties>
/// Id
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="GsecModel", Name="tbAirLine")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class tbAirLine : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new tbAirLine object.
/// </summary>
/// <param name="id">Initial value of Id.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public static tbAirLine CreatetbAirLine(long id)
{
tbAirLine tbAirLine = new tbAirLine();
tbAirLine.Id = id;
return tbAirLine;
}
/// <summary>
/// There are no comments for property Id in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public long Id
{
get
{
return this._Id;
}
set
{
this.OnIdChanging(value);
this.ReportPropertyChanging("Id");
this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("Id");
this.OnIdChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private long _Id;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnIdChanging(long value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnIdChanged();
/// <summary>
/// There are no comments for property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _Name;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnNameChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnNameChanged();
/// <summary>
/// There are no comments for property ShortName in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string ShortName
{
get
{
return this._ShortName;
}
set
{
this.OnShortNameChanging(value);
this.ReportPropertyChanging("ShortName");
this._ShortName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("ShortName");
this.OnShortNameChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _ShortName;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnShortNameChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnShortNameChanged();
/// <summary>
/// There are no comments for property Remark in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string Remark
{
get
{
return this._Remark;
}
set
{
this.OnRemarkChanging(value);
this.ReportPropertyChanging("Remark");
this._Remark = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Remark");
this.OnRemarkChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private string _Remark;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnRemarkChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnRemarkChanged();
}
And its give following error
Error 1 'System.Data.Objects.ObjectQuery' does not contain a definition for 'AddObject' and no extension method 'AddObject' accepting a first argument of type 'System.Data.Objects.ObjectQuery' could be found (are you missing a using directive or an assembly reference?)
.NET version 3.5 exposes ObjectQuery<T> versus ObjectSet<T> in .NET 4.0. Therefor you will need to use either e.AddTotbAirLines(tbAirLine) or e.AddObject("tbAirLines", tbAirLine). Both can be found on line 185 of the submitted generated code. In .NET 4.0 they decided to implement it like you were showing in your question.
I currently have a very annoying issue with updating a NopCommerce database from Entity Framework.
BACKGROUND:
I am writing a small tool to migrate one type of outdated ecommerce app to nopCommerce.
THE ERROR:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
WHAT I HAVE DONE TO TRY RESOLVE IT
In the past, this sort of error came up when I had a DateTime property that was uninitialized (year 0001).. but in this case, that is not the issue. I looked and made sure all the DateTime properties were being set. As that didn't work, I also tried making the db column datetime2(7) but no luck. Finally I set it to NULLABLE but it still gave me the same error. So, there's obviously something else going on here and EF is throwing some unhelpful error. I had wondered if there was perhaps an insert trigger (or any trigger for that matter) on the table which was trying to perhaps create an entry in the product variant table or another table where the datetime error was then coming from, but that is not the case.
THE CODE:
foreach (var piloProduct in piloProducts)
{
var product = new Models.Nop.Product
{
Name = piloProduct.Name,
ShortDescription = piloProduct.ShortDescription,
FullDescription = piloProduct.FullDescription,
ProductTemplateId = 1,
ShowOnHomePage = false,
MetaKeywords = piloProduct.MetaKeywords,
MetaDescription = piloProduct.MetaDescription,
MetaTitle = piloProduct.MetaTitle,
SeName = piloProduct.SeName,
AllowCustomerReviews = false,
ApprovedRatingSum = 0,
NotApprovedRatingSum = 0,
ApprovedTotalReviews = 0,
NotApprovedTotalReviews = 0,
Published = true,
Deleted = false,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow
};
nopDb.Products.AddObject(product);
}
nopDb.SaveChanges();
I'm at a complete loss with this one, as the above code is really simple and straightforward. Any help much appreciated.
UPDATE
I have just tried using Linq-To-SQL classes instead of Entity Framework EDMX, but had the exact same problem. The strange thing is, I ran an "INSERT INTO" statment on the table directly from SQL Management Studio but it worked.. go figure... is there any way to see exactly what "INSERT" statements are being generated by either EF or Linq-To-SQL?
And here's the EDMX generated model requested by Mark Oreta:
[EdmEntityTypeAttribute(NamespaceName="eSalesModel", Name="Product")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Product : EntityObject
{
public static Product CreateProduct(global::System.Int32 id, global::System.String name, global::System.Int32 productTemplateId, global::System.Boolean showOnHomePage, global::System.Boolean allowCustomerReviews, global::System.Int32 approvedRatingSum, global::System.Int32 notApprovedRatingSum, global::System.Int32 approvedTotalReviews, global::System.Int32 notApprovedTotalReviews, global::System.Boolean published, global::System.Boolean deleted)
{
Product product = new Product();
product.Id = id;
product.Name = name;
product.ProductTemplateId = productTemplateId;
product.ShowOnHomePage = showOnHomePage;
product.AllowCustomerReviews = allowCustomerReviews;
product.ApprovedRatingSum = approvedRatingSum;
product.NotApprovedRatingSum = notApprovedRatingSum;
product.ApprovedTotalReviews = approvedTotalReviews;
product.NotApprovedTotalReviews = notApprovedTotalReviews;
product.Published = published;
product.Deleted = deleted;
return product;
}
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Id
{
get
{
return _Id;
}
set
{
if (_Id != value)
{
OnIdChanging(value);
ReportPropertyChanging("Id");
_Id = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Id");
OnIdChanged();
}
}
}
private global::System.Int32 _Id;
partial void OnIdChanging(global::System.Int32 value);
partial void OnIdChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> PiloId
{
get
{
return _PiloId;
}
set
{
OnPiloIdChanging(value);
ReportPropertyChanging("PiloId");
_PiloId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("PiloId");
OnPiloIdChanged();
}
}
private Nullable<global::System.Int32> _PiloId;
partial void OnPiloIdChanging(Nullable<global::System.Int32> value);
partial void OnPiloIdChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Name
{
get
{
return _Name;
}
set
{
OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Name");
OnNameChanged();
}
}
private global::System.String _Name;
partial void OnNameChanging(global::System.String value);
partial void OnNameChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String ShortDescription
{
get
{
return _ShortDescription;
}
set
{
OnShortDescriptionChanging(value);
ReportPropertyChanging("ShortDescription");
_ShortDescription = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("ShortDescription");
OnShortDescriptionChanged();
}
}
private global::System.String _ShortDescription;
partial void OnShortDescriptionChanging(global::System.String value);
partial void OnShortDescriptionChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String FullDescription
{
get
{
return _FullDescription;
}
set
{
OnFullDescriptionChanging(value);
ReportPropertyChanging("FullDescription");
_FullDescription = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("FullDescription");
OnFullDescriptionChanged();
}
}
private global::System.String _FullDescription;
partial void OnFullDescriptionChanging(global::System.String value);
partial void OnFullDescriptionChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String AdminComment
{
get
{
return _AdminComment;
}
set
{
OnAdminCommentChanging(value);
ReportPropertyChanging("AdminComment");
_AdminComment = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("AdminComment");
OnAdminCommentChanged();
}
}
private global::System.String _AdminComment;
partial void OnAdminCommentChanging(global::System.String value);
partial void OnAdminCommentChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ProductTemplateId
{
get
{
return _ProductTemplateId;
}
set
{
OnProductTemplateIdChanging(value);
ReportPropertyChanging("ProductTemplateId");
_ProductTemplateId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ProductTemplateId");
OnProductTemplateIdChanged();
}
}
private global::System.Int32 _ProductTemplateId;
partial void OnProductTemplateIdChanging(global::System.Int32 value);
partial void OnProductTemplateIdChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Boolean ShowOnHomePage
{
get
{
return _ShowOnHomePage;
}
set
{
OnShowOnHomePageChanging(value);
ReportPropertyChanging("ShowOnHomePage");
_ShowOnHomePage = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ShowOnHomePage");
OnShowOnHomePageChanged();
}
}
private global::System.Boolean _ShowOnHomePage;
partial void OnShowOnHomePageChanging(global::System.Boolean value);
partial void OnShowOnHomePageChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String MetaKeywords
{
get
{
return _MetaKeywords;
}
set
{
OnMetaKeywordsChanging(value);
ReportPropertyChanging("MetaKeywords");
_MetaKeywords = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("MetaKeywords");
OnMetaKeywordsChanged();
}
}
private global::System.String _MetaKeywords;
partial void OnMetaKeywordsChanging(global::System.String value);
partial void OnMetaKeywordsChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String MetaDescription
{
get
{
return _MetaDescription;
}
set
{
OnMetaDescriptionChanging(value);
ReportPropertyChanging("MetaDescription");
_MetaDescription = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("MetaDescription");
OnMetaDescriptionChanged();
}
}
private global::System.String _MetaDescription;
partial void OnMetaDescriptionChanging(global::System.String value);
partial void OnMetaDescriptionChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String MetaTitle
{
get
{
return _MetaTitle;
}
set
{
OnMetaTitleChanging(value);
ReportPropertyChanging("MetaTitle");
_MetaTitle = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("MetaTitle");
OnMetaTitleChanged();
}
}
private global::System.String _MetaTitle;
partial void OnMetaTitleChanging(global::System.String value);
partial void OnMetaTitleChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String SeName
{
get
{
return _SeName;
}
set
{
OnSeNameChanging(value);
ReportPropertyChanging("SeName");
_SeName = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("SeName");
OnSeNameChanged();
}
}
private global::System.String _SeName;
partial void OnSeNameChanging(global::System.String value);
partial void OnSeNameChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Boolean AllowCustomerReviews
{
get
{
return _AllowCustomerReviews;
}
set
{
OnAllowCustomerReviewsChanging(value);
ReportPropertyChanging("AllowCustomerReviews");
_AllowCustomerReviews = StructuralObject.SetValidValue(value);
ReportPropertyChanged("AllowCustomerReviews");
OnAllowCustomerReviewsChanged();
}
}
private global::System.Boolean _AllowCustomerReviews;
partial void OnAllowCustomerReviewsChanging(global::System.Boolean value);
partial void OnAllowCustomerReviewsChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ApprovedRatingSum
{
get
{
return _ApprovedRatingSum;
}
set
{
OnApprovedRatingSumChanging(value);
ReportPropertyChanging("ApprovedRatingSum");
_ApprovedRatingSum = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ApprovedRatingSum");
OnApprovedRatingSumChanged();
}
}
private global::System.Int32 _ApprovedRatingSum;
partial void OnApprovedRatingSumChanging(global::System.Int32 value);
partial void OnApprovedRatingSumChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 NotApprovedRatingSum
{
get
{
return _NotApprovedRatingSum;
}
set
{
OnNotApprovedRatingSumChanging(value);
ReportPropertyChanging("NotApprovedRatingSum");
_NotApprovedRatingSum = StructuralObject.SetValidValue(value);
ReportPropertyChanged("NotApprovedRatingSum");
OnNotApprovedRatingSumChanged();
}
}
private global::System.Int32 _NotApprovedRatingSum;
partial void OnNotApprovedRatingSumChanging(global::System.Int32 value);
partial void OnNotApprovedRatingSumChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ApprovedTotalReviews
{
get
{
return _ApprovedTotalReviews;
}
set
{
OnApprovedTotalReviewsChanging(value);
ReportPropertyChanging("ApprovedTotalReviews");
_ApprovedTotalReviews = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ApprovedTotalReviews");
OnApprovedTotalReviewsChanged();
}
}
private global::System.Int32 _ApprovedTotalReviews;
partial void OnApprovedTotalReviewsChanging(global::System.Int32 value);
partial void OnApprovedTotalReviewsChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 NotApprovedTotalReviews
{
get
{
return _NotApprovedTotalReviews;
}
set
{
OnNotApprovedTotalReviewsChanging(value);
ReportPropertyChanging("NotApprovedTotalReviews");
_NotApprovedTotalReviews = StructuralObject.SetValidValue(value);
ReportPropertyChanged("NotApprovedTotalReviews");
OnNotApprovedTotalReviewsChanged();
}
}
private global::System.Int32 _NotApprovedTotalReviews;
partial void OnNotApprovedTotalReviewsChanging(global::System.Int32 value);
partial void OnNotApprovedTotalReviewsChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Boolean Published
{
get
{
return _Published;
}
set
{
OnPublishedChanging(value);
ReportPropertyChanging("Published");
_Published = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Published");
OnPublishedChanged();
}
}
private global::System.Boolean _Published;
partial void OnPublishedChanging(global::System.Boolean value);
partial void OnPublishedChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Boolean Deleted
{
get
{
return _Deleted;
}
set
{
OnDeletedChanging(value);
ReportPropertyChanging("Deleted");
_Deleted = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Deleted");
OnDeletedChanged();
}
}
private global::System.Boolean _Deleted;
partial void OnDeletedChanging(global::System.Boolean value);
partial void OnDeletedChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.DateTime> CreatedOnUtc
{
get
{
return _CreatedOnUtc;
}
set
{
OnCreatedOnUtcChanging(value);
ReportPropertyChanging("CreatedOnUtc");
_CreatedOnUtc = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CreatedOnUtc");
OnCreatedOnUtcChanged();
}
}
private Nullable<global::System.DateTime> _CreatedOnUtc;
partial void OnCreatedOnUtcChanging(Nullable<global::System.DateTime> value);
partial void OnCreatedOnUtcChanged();
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.DateTime> UpdatedOnUtc
{
get
{
return _UpdatedOnUtc;
}
set
{
OnUpdatedOnUtcChanging(value);
ReportPropertyChanging("UpdatedOnUtc");
_UpdatedOnUtc = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UpdatedOnUtc");
OnUpdatedOnUtcChanged();
}
}
private Nullable<global::System.DateTime> _UpdatedOnUtc;
partial void OnUpdatedOnUtcChanging(Nullable<global::System.DateTime> value);
partial void OnUpdatedOnUtcChanged();
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductCategory_Product", "Product_Category_Mapping")]
public EntityCollection<Product_Category_Mapping> Product_Category_Mapping
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product_Category_Mapping>("eSalesModel.ProductCategory_Product", "Product_Category_Mapping");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product_Category_Mapping>("eSalesModel.ProductCategory_Product", "Product_Category_Mapping", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductManufacturer_Product", "Product_Manufacturer_Mapping")]
public EntityCollection<Product_Manufacturer_Mapping> Product_Manufacturer_Mapping
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product_Manufacturer_Mapping>("eSalesModel.ProductManufacturer_Product", "Product_Manufacturer_Mapping");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product_Manufacturer_Mapping>("eSalesModel.ProductManufacturer_Product", "Product_Manufacturer_Mapping", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductPicture_Product", "Product_Picture_Mapping")]
public EntityCollection<Product_Picture_Mapping> Product_Picture_Mapping
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product_Picture_Mapping>("eSalesModel.ProductPicture_Product", "Product_Picture_Mapping");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product_Picture_Mapping>("eSalesModel.ProductPicture_Product", "Product_Picture_Mapping", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductReview_Product1", "ProductReview")]
public EntityCollection<ProductReview> ProductReviews
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ProductReview>("eSalesModel.ProductReview_Product1", "ProductReview");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ProductReview>("eSalesModel.ProductReview_Product1", "ProductReview", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductSpecificationAttribute_Product", "Product_SpecificationAttribute_Mapping")]
public EntityCollection<Product_SpecificationAttribute_Mapping> Product_SpecificationAttribute_Mapping
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product_SpecificationAttribute_Mapping>("eSalesModel.ProductSpecificationAttribute_Product", "Product_SpecificationAttribute_Mapping");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product_SpecificationAttribute_Mapping>("eSalesModel.ProductSpecificationAttribute_Product", "Product_SpecificationAttribute_Mapping", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "ProductVariant_Product", "ProductVariant")]
public EntityCollection<ProductVariant> ProductVariants
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ProductVariant>("eSalesModel.ProductVariant_Product", "ProductVariant");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ProductVariant>("eSalesModel.ProductVariant_Product", "ProductVariant", value);
}
}
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("eSalesModel", "Product_ProductTag_Mapping", "ProductTag")]
public EntityCollection<ProductTag> ProductTags
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ProductTag>("eSalesModel.Product_ProductTag_Mapping", "ProductTag");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ProductTag>("eSalesModel.Product_ProductTag_Mapping", "ProductTag", value);
}
}
}
}
Right, I figured out what was going on.. basically, I am running this all in a Transaction and I was exporting other entities (categories) before the products. The problem is that i did not call SaveChanges() after adding all the Categories... so the error that was coming up was with regards to the Categories table and not the Products table, but I only got the message when I called SaveChanges() which was after I added the Products as well.. very confusing.. I hope in future they will make it clearer by saying which table the error was coming from.. that would save a lot of time.
This is my situation and not you can see why I didn't immediately pick up what was wrong:
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(30)))
using (var piloDB = new PiloEntities())
using (var eSalesDB = new ESalesEntities())
{
ExportCategories(piloDB, eSalesDB); //SaveChanges() not called in here
ExportProducts(piloDB, eSalesDB); //SaveChanges() is called in here
//export other...