I am using Entity Framework for mapping our company software' and what i would like create a sort of conditional field mapping based on some field attributes i have created. Trying to better explain:
I have created the attribute ModelPersistentAttribute that I use in the following way:
[ModelPersistent("WORKORDER", persistentSchema: "mySchema", fromVersion: "0.0", toVersion: "2.0")]
public class WorkOrderDTO : AMOSEntityDTO
{
public WorkOrderDTO()
{ }
public WorkOrderDTO(decimal WORKORDERID, string WONO, DateTime LASTUPDATED)
{
this.WORKORDERID = WORKORDERID;
this.WONO = WONO;
this.LASTUPDATED = LASTUPDATED;
}
[Key]
public decimal WORKORDERID { get; set; }
public string WONO { get; set; }
[ModelPersistentAttribute(persistentName: "TITLE", fromVersion:"0.0")]
public string myTITLE { get; set; }
}
Then I created a mapping class that has an automap method which is the following
/// <summary>
/// Automapping
/// </summary>
/// <param name="configurationOptions"></param>
protected void AutoMap(EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
{
IEnumerable<ModelPersistentAttribute> persistentAttributes = typeof(TEntity).GetCustomAttributes<ModelPersistentAttribute>();
if (persistentAttributes.Count() == 0 || persistentAttributes.Any(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType)))
{
if (persistentAttributes.Count() != 0) MapEntity(entityConfigurationOptions, persistentAttributes);
foreach (var prop in typeof(TEntity).GetProperties())
{
NotMappedAttribute notMapped = prop.GetCustomAttribute<NotMappedAttribute>();
if (notMapped == null)
{
IEnumerable<ModelPersistentAttribute> modelAttributes = prop.GetCustomAttributes<ModelPersistentAttribute>();
if (modelAttributes.Count() == 0 || (modelAttributes.Any(ma => ma.IsInRange(entityConfigurationOptions.Version))))
MapProperty(prop, entityConfigurationOptions, modelAttributes);
else
IgnoreProperty(prop, entityConfigurationOptions);
}
}
}
else
IgnoreEntity(entityConfigurationOptions);
}
Everything seems to work properly for mapping
protected virtual void MapProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions, IEnumerable<ModelPersistentAttribute> modelAttributes)
{
ModelPersistentAttribute modelVersionAttribute = modelAttributes.FirstOrDefault<ModelPersistentAttribute>(mpa => mpa.IsInRange(entityConfigurationOptions.Version, entityConfigurationOptions.DBMSType));
string persistentName = string.Empty;
if (modelVersionAttribute != null)
persistentName = modelVersionAttribute.PersistentName;
else
persistentName = propertyInfo.Name;
entityConfigurationOptions.ModelBuilder.Properties().Where(p => p.Equals(propertyInfo)).Configure(c=> c.HasColumnName(persistentName));
}
but I am not able to run it when i want to ignore a property:
/// <summary>
/// Ignore property
/// </summary>
/// <param name="propertyInfo"></param>
protected virtual void IgnoreProperty(PropertyInfo propertyInfo, EntityTypeMapCondigurationOptionsEFNet<TEntity> entityConfigurationOptions)
{
entityConfigurationOptions.ModelBuilder.Types<TEntity>().Configure(ctc => ctc.Ignore(p => propertyInfo));
// The following as well doesn't work
//entityConfigurationOptions.ModelBuilder.Types<TEntity>//().Configure(ctc => ctc.Ignore(p => propertyInfo.Name));
}
The meaning of the error I get is something that I understand but I don't know how to solve:
The expression 'p => value(DTO.Service.EFCore.EntityTypeVersionMap`1+<>c__DisplayClass4_0[TestDTO.Shared.WorkOrderDTO]).propertyInfo' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'.'
Any help on this will be VERY appreciated!
Thanks in advance
Luigi
You can use the non generic Types method with Where, which Configure -> Ignore method has overloads for string propertyName and PropertyInfo propertyInfo (the one that you need):
entityConfigurationOptions.ModelBuilder
.Types().Where(type => type == typeof(TEntity))
.Configure(ctc => ctc.Ignore(propertyInfo));
Related
I'm using EF 4.3.1 and I'm doing my first implementation of Code First and testing the data. Here's my setup trying to implement eager loading.
public class Model
{
public int Id { get; set; }
public ICollection<ModelArchive> ModelArchives { get; set; }
}
public class ModelArchive
{
public int Id { get; set; }
public ICollection<Option> Options { get; set; }
}
public class Option
{
public int Id { get; set; }
public bool Deleted { get; set; }
}
I'd like to be able to only select the Options where Deleted == false in my query. So far I'm coming up empty or it results in an exception when running the query.
Here's my current query:
using (var db = new ModelContainer())
{
db.Configuration.LazyLoadingEnabled = false;
var model = db.Models.Where(m => m.Id == 3)
.Include(m => m.ModelArchives.Select(o => o.Option).Where(o => o.Deleted == false));
}
Exception: Message = "The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.\r\nParameter name: path"
Any help would be appreciated.
You can't load filtered data with Entity Framework. Navigation properties either contain all related entities, or none of them.
Consider to do manual join and return anonymous objects with not deleted options.
You can try
using (var db = new ModelContainer())
{
//db.Configuration.LazyLoadingEnabled = false;
var model = db.Models.Where(m => m.Id == 3 && m.ModelArchives.Option.Deleted==false)
.Include(m => m.ModelArchives.Option);
}
You can use generic function to get the data
public List<T> IncludeMultipleWithWhere(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
{
IQueryable<T> itemWithIncludes = dbContext.Set<T>() as IQueryable<T>;
try
{
if (includes != null)
{
itemWithIncludes = includes.Aggregate(itemWithIncludes,
(current, include) => current.Include(include)).Where(predicate);
}
}
catch (Exception ex)
{
}
finally { }
return itemWithIncludes.ToList();
}
your calling function just need to passing the parameter like
Expression<Func<Models, bool>> whereCond1 = (m) => m.Id == 3 && m.ModelArchives.Option.Deleted==false;
Expression<Func<Models, object>>[] includeMulti = { m => m.ModelArchives.Option };
You were correct in disabling lazyloading.
But then you have to filter the navigation property in a subquery, and EF will magically attach it to your main query. Here is something that should work
using (var db = new ModelContainer())
{
db.Configuration.LazyLoadingEnabled = false;
var filteredModelArchives = db.ModelArchives.Select(o => o.Option).Where(o => o.Deleted == false).Include("Options");
var model = db.Models.Where(m => m.Id == 3);
}
I want to store an object that contains a List of primitives using EF.
public class MyObject {
public int Id {get;set;}
public virtual IList<int> Numbers {get;set;}
}
I know that EF cannot store this, but I'd like to know possible solutions to solve this problem.
The 2 Solutions I can think of are:
1.Create a Dummy object that has an Id and the Integervalue, e.g.
public class MyObject {
public int Id {get;set;}
public virtual IList<MyInt> Numbers {get;set;}
}
public class MyInt {
public int Id {get;set;}
public int Number {get;set;}
}
2.Store the list values as a blob, e.g.
public class MyObject {
public int Id {get;set;}
/// use NumbersValue to persist/load the list values
public string NumbersValue {get;set;}
[NotMapped]
public virtual IList<int> Numbers {
get {
return NumbersValue.split(',');
}
set {
NumbersValue = value.ToArray().Join(",");
}
}
}
The Problem with the 2. approach is, that I have to create a Custom IList implementation to keep track if someone modifies the returned collection.
Is there a better solution for this?
Although I do not like to answer my own question, but here is what solved my problem:
After I found this link about Complex Types I tried several implementations, and after some headache I ended up with this.
The List values get stored as a string on the table directly, so it's not required to perform several joins in order to get the list entries. Implementors only have to implement the conversation for each list entry to a persistable string (see the Code example).
Most of the code is handled in the Baseclass (PersistableScalarCollection). You only have to derive from it per datatype (int, string, etc) and implement the method to serialize/deserialize the value.
It's important to note, that you cannot use the the generic baseclass directly (when you remove the abstract). It seems that EF cannot work with that. You also have to make sure to annotate the derived class with the [ComplexType] attribute.
Also note that it seems not to be possible to implement a ComplexType for IList<T> because EF complains about the Indexer (therefore I went on with ICollection).
It's also important to note, that since everything is stored within one column, you cannot search for values in the Collection (at least on the database). In this case you may skip this implementation or denormalize the data for searching.
Example for a Collection of integers:
/// <summary>
/// ALlows persisting of a simple integer collection.
/// </summary>
[ComplexType]
public class PersistableIntCollection : PersistableScalarCollection<int> {
protected override int ConvertSingleValueToRuntime(string rawValue) {
return int.Parse(rawValue);
}
protected override string ConvertSingleValueToPersistable(int value) {
return value.ToString();
}
}
Usage example:
public class MyObject {
public int Id {get;set;}
public virtual PersistableIntCollection Numbers {get;set;}
}
This is the baseclass that handles the persistence aspect by storing the list entries within a string:
/// <summary>
/// Baseclass that allows persisting of scalar values as a collection (which is not supported by EF 4.3)
/// </summary>
/// <typeparam name="T">Type of the single collection entry that should be persisted.</typeparam>
[ComplexType]
public abstract class PersistableScalarCollection<T> : ICollection<T> {
// use a character that will not occur in the collection.
// this can be overriden using the given abstract methods (e.g. for list of strings).
const string DefaultValueSeperator = "|";
readonly string[] DefaultValueSeperators = new string[] { DefaultValueSeperator };
/// <summary>
/// The internal data container for the list data.
/// </summary>
private List<T> Data { get; set; }
public PersistableScalarCollection() {
Data = new List<T>();
}
/// <summary>
/// Implementors have to convert the given value raw value to the correct runtime-type.
/// </summary>
/// <param name="rawValue">the already seperated raw value from the database</param>
/// <returns></returns>
protected abstract T ConvertSingleValueToRuntime(string rawValue);
/// <summary>
/// Implementors should convert the given runtime value to a persistable form.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected abstract string ConvertSingleValueToPersistable(T value);
/// <summary>
/// Deriving classes can override the string that is used to seperate single values
/// </summary>
protected virtual string ValueSeperator {
get {
return DefaultValueSeperator;
}
}
/// <summary>
/// Deriving classes can override the string that is used to seperate single values
/// </summary>
protected virtual string[] ValueSeperators {
get {
return DefaultValueSeperators;
}
}
/// <summary>
/// DO NOT Modeify manually! This is only used to store/load the data.
/// </summary>
public string SerializedValue {
get {
var serializedValue = string.Join(ValueSeperator.ToString(),
Data.Select(x => ConvertSingleValueToPersistable(x))
.ToArray());
return serializedValue;
}
set {
Data.Clear();
if (string.IsNullOrEmpty(value)) {
return;
}
Data = new List<T>(value.Split(ValueSeperators, StringSplitOptions.None)
.Select(x => ConvertSingleValueToRuntime(x)));
}
}
#region ICollection<T> Members
public void Add(T item) {
Data.Add(item);
}
public void Clear() {
Data.Clear();
}
public bool Contains(T item) {
return Data.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex) {
Data.CopyTo(array, arrayIndex);
}
public int Count {
get { return Data.Count; }
}
public bool IsReadOnly {
get { return false; }
}
public bool Remove(T item) {
return Data.Remove(item);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator() {
return Data.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return Data.GetEnumerator();
}
#endregion
}
I'm using EF Core and had a similar problem but solved it in a simpler way.
The idea is to store the list of integers as a comma separated string in the database. I do that by specifying a ValueConverter in my entity type builder.
public class MyObjectBuilder : IEntityTypeConfiguration<MyObject>
{
public void Configure(EntityTypeBuilder<MyObject> builder)
{
var intArrayValueConverter = new ValueConverter<int[], string>(
i => string.Join(",", i),
s => string.IsNullOrWhiteSpace(s) ? new int[0] : s.Split(new[] { ',' }).Select(v => int.Parse(v)).ToArray());
builder.Property(x => x.Numbers).HasConversion(intArrayValueConverter);
}
}
More information can be found here: https://entityframeworkcore.com/knowledge-base/37370476/how-to-persist-a-list-of-strings-with-entity-framework-core-
Bernhard's answer is brilliant. I just couldn't help but refine it a little. Here's my two cents:
[ComplexType]
public abstract class EFPrimitiveCollection<T> : IList<T>
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
const string DefaultValueSeperator = "|";
readonly string[] DefaultValueSeperators = new string[] { DefaultValueSeperator };
[NotMapped]
private List<T> _data;
[NotMapped]
private string _value;
[NotMapped]
private bool _loaded;
protected virtual string ValueSeparator => DefaultValueSeperator;
protected virtual string[] ValueSeperators => DefaultValueSeperators;
[ShadowColumn, MaxLength]
protected virtual string Value // Change this to public if you prefer not to use the ShadowColumnAttribute
{
get => _value;
set
{
_data.Clear();
_value = value;
if (string.IsNullOrWhiteSpace(_value))
return;
_data = _value.Split(ValueSeperators, StringSplitOptions.None)
.Select(x => ConvertFromString(x)).ToList();
if (!_loaded) _loaded = true;
}
}
public EFPrimitiveCollection()
{
_data = new List<T>();
}
void UpdateValue()
{
_value = string.Join(ValueSeparator.ToString(),
_data.Select(x => ConvertToString(x))
.ToArray());
}
public abstract T ConvertFromString(string value);
public abstract string ConvertToString(T value);
#region IList Implementation
public int Count
{
get
{
EnsureData();
return _data.Count;
}
}
public T this[int index]
{
get
{
EnsureData();
return _data[index];
}
set
{
EnsureData();
_data[index] = value;
}
}
public bool IsReadOnly => false;
void EnsureData()
{
if (_loaded)
return;
if (string.IsNullOrWhiteSpace(_value))
return;
if (_data.Count > 0) return;
if (!_loaded) _loaded = true;
_data = _value.Split(ValueSeperators, StringSplitOptions.None)
.Select(x => ConvertFromString(x)).ToList();
}
public void Add(T item)
{
EnsureData();
_data.Add(item);
UpdateValue();
}
public bool Remove(T item)
{
EnsureData();
bool res = _data.Remove(item);
UpdateValue();
return res;
}
public void Clear()
{
_data.Clear();
UpdateValue();
}
public bool Contains(T item)
{
EnsureData();
return _data.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
EnsureData();
_data.CopyTo(array, arrayIndex);
}
public int IndexOf(T item)
{
EnsureData();
return _data.IndexOf(item);
}
public void Insert(int index, T item)
{
EnsureData();
_data.Insert(index, item);
UpdateValue();
}
public void RemoveAt(int index)
{
EnsureData();
_data.RemoveAt(index);
UpdateValue();
}
public void AddRange(IEnumerable<T> collection)
{
EnsureData();
_data.AddRange(collection);
UpdateValue();
}
public IEnumerator<T> GetEnumerator()
{
EnsureData();
return _data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
EnsureData();
return _data.GetEnumerator();
}
#endregion
}
With that base class you can have as many derivations as you like:
[ComplexType]
public class EFIntCollection : EFPrimitiveCollection<int>
{
public override int ConvertFromString(string value) => int.Parse(value);
public override string ConvertToString(int value) => value.ToString();
}
[ComplexType]
public class EFInt64Collection : EFPrimitiveCollection<long>
{
public override long ConvertFromString(string value) => long.Parse(value);
public override string ConvertToString(long value) => value.ToString();
}
[ComplexType]
public class EFStringCollection : EFPrimitiveCollection<string>
{
string _separator;
protected override string ValueSeparator => _separator ?? base.ValueSeparator;
public override string ConvertFromString(string value) => value;
public override string ConvertToString(string value) => value;
public EFStringCollection()
{
}
public EFStringCollection(string separator)
{
_separator = separator;
}
}
EFPrimitiveCollection works just like a list, so you shouldn't have any issues using it like a normal List. Also the data is loaded on demand.
Here's an example:
if (store.AcceptedZipCodes == null)
store.AcceptedZipCodes = new EFStringCollection();
store.AcceptedZipCodes.Clear();
store.AcceptedZipCodes.AddRange(codes.Select(x => x.Code));
Shadow Column
This attribute is being used to abstract away the Value property. If you do not see the need to do this, simply remove it and make the Value property public.
More information can be found on the ShadowColumnAttribute in my answer here
The simple solution would be in your DataContext (a class that implements DbContext) add this override:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<MyObject>()
.Property(p => p.Numbers)
.HasConversion(
toDb => string.Join(",", toDb),
fromDb => fromDb.Split(',').Select(Int32.Parse).ToList() ?? new List<int>());
}
I am trying to create a basic example using Entity Framework to do the mapping of the output of a SQL Server Stored procedure to an entity in C#, but the entity has differently (friendly) names parameters as opposed to the more cryptic names. I am also trying to do this with the Fluent (i.e. non edmx) syntax.
What works ....
The stored procedure returns values called: UT_ID, UT_LONG_NM, UT_STR_AD, UT_CITY_AD, UT_ST_AD, UT_ZIP_CD_AD, UT_CT
If I create an object like this ...
public class DBUnitEntity
{
public Int16 UT_ID { get; set; }
public string UT_LONG_NM { get; set; }
public string UT_STR_AD { get; set; }
public string UT_CITY_AD { get; set; }
public string UT_ST_AD { get; set; }
public Int32 UT_ZIP_CD_AD { get; set; }
public string UT_CT { get; set; }
}
and an EntityTypeConfiguration like this ...
public class DbUnitMapping: EntityTypeConfiguration<DBUnitEntity>
{
public DbUnitMapping()
{
HasKey(t => t.UT_ID);
}
}
... which I add in the OnModelCreating of the DbContext, then I can get the entities just fine out of the database, which is nice, using this ....
var allUnits = _context.Database.SqlQuery<DBUnitEntity>(StoredProcedureHelper.GetAllUnitsProc);
BUT, What Doesn't Work
If I want an entity like this, with friendlier names ....
public class UnitEntity : IUnit
{
public Int16 UnitId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public Int32 Zip { get; set; }
public string Category { get; set; }
}
and an EntityTypeConfiguration like this ...
public UnitMapping()
{
HasKey(t => t.UnitId);
Property(t => t.UnitId).HasColumnName("UT_ID");
Property(t => t.Name).HasColumnName("UT_LONG_NM");
Property(t => t.Address).HasColumnName("UT_STR_AD");
Property(t => t.City).HasColumnName("UT_CITY_AD");
Property(t => t.State).HasColumnName("UT_ST_AD");
Property(t => t.Zip).HasColumnName("UT_ZIP_CD_AD");
Property(t => t.Category).HasColumnName("UT_CT");
}
When I try to get the data I get a System.Data.EntityCommandExecutionException with the message ....
"The data reader is incompatible with the specified 'DataAccess.EFCodeFirstSample.UnitEntity'. A member of the type, 'UnitId', does not have a corresponding column in the data reader with the same name."
If I add the "stored procedure named" property to the entity, it goes and complains about the next "unknown" property.
Does "HasColumnName" not work as I expect/want it to in this code-first stored procedure fluent style of EF?
Update:
Tried using DataAnnotations (Key from ComponentModel, and Column from EntityFramework) ... ala
public class UnitEntity : IUnit
{
[Key]
[Column("UT_ID")]
public Int16 UnitId { get; set; }
public string Name { get; set; }
That did remove the need for any EntityTypeConfiguration at all for the DBUnitEntity with the database-identical naming (i.e. just adding the [Key] Attribute), but did nothing for the entity with the property names that don't match the database (same error as before).
I don't mind using the ComponentModel Annotations in the Model, but I really don't want to use the EntityFramework Annotations in the model if I can help it (don't want to tie the Model to any specific data access framework)
From Entity Framework Code First book (page 155):
The SQLQuery method always attempts the column-to-property matching based on property name...
None that the column-to-property name matching does not take any mapping into account. For example, if you had mapped the DestinationId property to a column called Id in the Destination table, the SqlQuery method would not use this mapping.
So you cannot use mappings when calling stored procedure. One workaround is to modify your stored procedure to return result with aliases for each column that will match your object properties' names.
Select UT_STR_AD as Address From SomeTable etc
This isn't using Entity Framework but it is stemming from dbcontext. I have spent hours upon hours scouring the internet and using dot peek all for nothing. I read some where that the ColumnAttribute is ignored for SqlQueryRaw. But I have crafted up something with reflection, generics, sql datareader, and Activator. I am going to be testing it on a few other procs. If there is any other error checking that should go in, comment.
public static List<T> SqlQuery<T>( DbContext db, string sql, params object[] parameters)
{
List<T> Rows = new List<T>();
using (SqlConnection con = new SqlConnection(db.Database.Connection.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
cmd.Parameters.Add(param);
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
var dictionary = typeof(T).GetProperties().ToDictionary(
field => CamelCaseToUnderscore(field.Name), field => field.Name);
while (dr.Read())
{
T tempObj = (T)Activator.CreateInstance(typeof(T));
foreach (var key in dictionary.Keys)
{
PropertyInfo propertyInfo = tempObj.GetType().GetProperty(dictionary[key], BindingFlags.Public | BindingFlags.Instance);
if (null != propertyInfo && propertyInfo.CanWrite)
propertyInfo.SetValue(tempObj, Convert.ChangeType(dr[key], propertyInfo.PropertyType), null);
}
Rows.Add(tempObj);
}
}
dr.Close();
}
}
}
return Rows;
}
private static string CamelCaseToUnderscore(string str)
{
return Regex.Replace(str, #"(?<!_)([A-Z])", "_$1").TrimStart('_').ToLower();
}
Also something to know is that all of our stored procs return lowercase underscore delimited. The CamelCaseToUnderscore is built specifically for it.
Now BigDeal can map to big_deal
You should be able to call it like so
Namespace.SqlQuery<YourObj>(db, "name_of_stored_proc", new SqlParameter("#param",value),,,,,,,);
The example posted by "DeadlyChambers" is great but I would like to extend the example to include the ColumnAttribute that you can use with EF to add to a properties to map a SQL field to a Class property.
Ex.
[Column("sqlFieldName")]
public string AdjustedName { get; set; }
Here is the modified code.
This code also include a parameter to allow for custom mappings if needed by passing a dictionary.
You will need a Type Converter other than Convert.ChangeType for things like nullable types.
Ex. If you have a field that is bit in the database and nullable boolean in .NET you will get a type convert issue.
/// <summary>
/// WARNING: EF does not use the ColumnAttribute when mapping from SqlQuery. So this is a "fix" that uses "lots" of REFLECTION
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="database"></param>
/// <param name="sqlCommandString"></param>
/// <param name="modelPropertyName_sqlPropertyName">Model Property Name and SQL Property Name</param>
/// <param name="sqlParameters">SQL Parameters</param>
/// <returns></returns>
public static List<T> SqlQueryMapped<T>(this System.Data.Entity.Database database,
string sqlCommandString,
Dictionary<string,string> modelPropertyName_sqlPropertyName,
params System.Data.SqlClient.SqlParameter[] sqlParameters)
{
List<T> listOfT = new List<T>();
using (var cmd = database.Connection.CreateCommand())
{
cmd.CommandText = sqlCommandString;
if (cmd.Connection.State != System.Data.ConnectionState.Open)
{
cmd.Connection.Open();
}
cmd.Parameters.AddRange(sqlParameters);
using (var dataReader = cmd.ExecuteReader())
{
if (dataReader.HasRows)
{
// HACK: you can't use extension methods without a type at design time. So this is a way to call an extension method through reflection.
var convertTo = typeof(GenericExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(mi => mi.Name == "ConvertTo").Where(m => m.GetParameters().Count() == 1).FirstOrDefault();
// now build a new list of the SQL properties to map
// NOTE: this method is used because GetOrdinal can throw an exception if column is not found by name
Dictionary<string, int> sqlPropertiesAttributes = new Dictionary<string, int>();
for (int index = 0; index < dataReader.FieldCount; index++)
{
sqlPropertiesAttributes.Add(dataReader.GetName(index), index);
}
while (dataReader.Read())
{
// create a new instance of T
T newT = (T)Activator.CreateInstance(typeof(T));
// get a list of the model properties
var modelProperties = newT.GetType().GetProperties();
// now map the SQL property to the EF property
foreach (var propertyInfo in modelProperties)
{
if (propertyInfo != null && propertyInfo.CanWrite)
{
// determine if the given model property has a different map then the one based on the column attribute
string sqlPropertyToMap = (propertyInfo.GetCustomAttribute<ColumnAttribute>()?.Name ?? propertyInfo.Name);
string sqlPropertyName;
if (modelPropertyName_sqlPropertyName!= null && modelPropertyName_sqlPropertyName.TryGetValue(propertyInfo.Name, out sqlPropertyName))
{
sqlPropertyToMap = sqlPropertyName;
}
// find the SQL value based on the column name or the property name
int columnIndex;
if (sqlPropertiesAttributes.TryGetValue(sqlPropertyToMap, out columnIndex))
{
var sqlValue = dataReader.GetValue(columnIndex);
// ignore this property if it is DBNull
if (Convert.IsDBNull(sqlValue))
{
continue;
}
// HACK: you can't use extension methods without a type at design time. So this is a way to call an extension method through reflection.
var newValue = convertTo.MakeGenericMethod(propertyInfo.PropertyType).Invoke(null, new object[] { sqlValue });
propertyInfo.SetValue(newT, newValue);
}
}
}
listOfT.Add(newT);
}
}
}
}
return listOfT;
}
I've read some other posts but they have not helped.
CarPart is an EF4 gened class
[EdmEntityTypeAttribute(NamespaceName="xxxx.Data.Domain.Model", Name="CarPart")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class CarPart : EntityObject
{
#region Factory Method
/// summary>
/// Create a new CarPart object.
/// </summary>
/// <param name="carPartId">Initial value of the CarPartId property.</param>
/// <param name="name">Initial value of the Name property.</param>
/// <param name="carPartTypeId">Initial value of the CarPartId property.</param>
public static CarPart CreateCarPart(global::System.Int32 carPartId, global::System.String name, global::System.Int32 carPartId)
{
CarPart carPart = new CarPart();
carPart.CarPartId = carPartId;
carPart.Name = name;
carPart.CarPartTypeId = carPartTypeId;
return carPart;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 CarPartId
{
get
{
return _CarPartId;
}
set
{
if (_CarPartId != value)
{
OnCarPartIdChanging(value);
ReportPropertyChanging("CarPartId");
_CarPartId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CarPartIdId");
OnCarPartIdChanged();
}
}
}
private global::System.Int32 _CarPartId;
partial void OnCarPartIdChanging(global::System.Int32 value);
partial void OnCarPartIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[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();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 CarPartTypeId
{
get
{
return _CarPartTypeId;
}
set
{
OnCarPartTypeIdChanging(value);
ReportPropertyChanging("CarPartTypeId");
_CarPartTypeId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CarPartTypeId");
OnCarPartTypeIdChanged();
}
}
private global::System.Int32 _CarPartTypeId;
partial void OnCarPartTypeIdChanging(global::System.Int32 value);
partial void OnCarPartTypeIdChanged();
#endregion
#region Navigation Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("xxxx.Data.Domain.Model", "FK_CarPartId", "Part")]
public EntityCollection<Part> Parts
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Part>("xxxxx.Data.Domain.Model.FK_CarPartId", "Part");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Part>("xxxx.Data.Domain.Model.FK_CarPartId", "Part", value);
}
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("xxxxx.Data.Domain.Model", "FK_CarPartTypeId", "CarPartType")]
public CarPartType CarPartType
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CarPartType>("xxxx.Data.Domain.Model.FK_CarPartTypeId", "CarPartType").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CarPartType>("xxxxx.Data.Domain.Model.FK_CarPartTypeId", "CarPartType").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<CarPartType> CarPartTypeReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CarPartType>("xxxx.Data.Domain.Model.FK_CarPartTypeId", "CarPartType");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<CarPartType>("xxxxxx.Data.Domain.Model.FK_CarPartTypeId", "CarPartType", value);
}
}
}
#endregion
}
So here's my join code:
List<Parts> parts = _context.Parts.Where(p => p.PartId == partId).ToList();
List<CarParts> parts = _context.CarParts
.Join(parts, cp => cp.PartId, p => p.PartId, (cp, p) => cp).ToList();
Error: Unable to create a constant value of type 'Model.CarParts'. Only
primitive types ('such as Int32, String, and Guid') are supported in
this context.
Tried to look at it but can't get past this. I'm a bit new to LINQ-To-SQL..done a fair amount but not a ton (mostly done LINQ to Objects) so new to joins with this.
if i'm understanding right you want to do something like this:
internal class Db
{
public Db()
{
var parts = new List<Part>
{
new Part() {PartId = 1, PartName = "Part 1"},
new Part() {PartId = 2, PartName = "Part 2"},
};
Parts = parts.AsQueryable();
var carParts = new List<CarPart>
{
new CarPart() {CarPartId = 1, CarPartName = "Car Part 1.1", PartId = 1},
new CarPart() {CarPartId = 1, CarPartName = "Car Part 1.2", PartId = 1},
new CarPart() {CarPartId = 1, CarPartName = "Car Part 2.1", PartId = 2},
};
CarParts = carParts.AsQueryable();
}
public IQueryable<Part> Parts { get; set; }
public IQueryable<CarPart> CarParts { get; set; }
}
internal class CarPart
{
public int CarPartId { get; set; }
public string CarPartName { get; set; }
public int PartId { get; set; }
}
internal class Part
{
public int PartId { get; set; }
public string PartName { get; set; }
}
static void Main(string[] args)
{
Db db = new Db();
var result = from carPart in db.CarParts
join part in db.Parts on carPart.PartId equals part.PartId
select new {Part = part, CarPart = carPart};
var lambdaResult = db.CarParts.Join(db.Parts, part => part.PartId, caPart => caPart.PartId,
(carPart, part) => new {CarPart = carPart, Part = part});
foreach (var item in result)
{
Console.WriteLine(item.Part.PartName);
Console.WriteLine(item.CarPart.CarPartName);
}
Console.WriteLine("------------");
foreach (var item in lambdaResult)
{
Console.WriteLine(item.Part.PartName);
Console.WriteLine(item.CarPart.CarPartName);
}
}
the result is a new anonymous object with the joined objects as content.
it would print this to the console:
Part 1
Car Part 1.1
Part 1
Car Part 1.2
Part 2
Car Part 2.1
-------
Part 1
Car Part 1.1
Part 1
Car Part 1.2
Part 2
Car Part 2.1
class DemoUser
{
[TitleCase]
public string FirstName { get; set; }
[TitleCase]
public string LastName { get; set; }
[UpperCase]
public string Salutation { get; set; }
[LowerCase]
public string Email { get; set; }
}
Suppose i have demo-class as written above, i want to create some custom annotations like LowerCase,UpperCase etc so that its value gets converted automatically. Doing this will enable me to use these annotations in other classes too.
As Ladislav implied, this is two questions in one.
Assuming you follow the recipe for creating attributes in Jefim's link, and assuming you're calling those created attribute classes "UpperCaseAttribute", "LowerCaseAttribute", and "TitleCaseAttribute", the following SaveChanges() override should work in EF 4.3 (the current version as of the time of this answer post).
public override int SaveChanges()
{
IEnumerable<DbEntityEntry> changedEntities = ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Added || e.State == System.Data.EntityState.Modified);
TextInfo textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;
changedEntities.ToList().ForEach(entry =>
{
var properties = from attributedProperty in entry.Entity.GetType().GetProperties()
where attributedProperty.PropertyType == typeof (string)
select new { entry, attributedProperty,
attributes = attributedProperty.GetCustomAttributes(true)
.Where(attribute => attribute is UpperCaseAttribute || attribute is LowerCaseAttribute || attribute is TitleCaseAttribute)
};
properties = properties.Where(p => p.attributes.Count() > 1);
properties.ToList().ForEach(p =>
{
p.attributes.ToList().ForEach(att =>
{
if (att is UpperCaseAttribute)
{
p.entry.CurrentValues[p.attributedProperty.Name] = textInfo.ToUpper(((string)p.entry.CurrentValues[p.attributedProperty.Name]));
}
if (att is LowerCaseAttribute)
{
p.entry.CurrentValues[p.attributedProperty.Name] = textInfo.ToLower(((string)p.entry.CurrentValues[p.attributedProperty.Name]));
}
if (att is TitleCaseAttribute)
{
p.entry.CurrentValues[p.attributedProperty.Name] = textInfo.ToTitleCase(((string)p.entry.CurrentValues[p.attributedProperty.Name]));
}
});
});
});
return base.SaveChanges();
}
You can override the SaveChanges method in your EF context (if you use default code-generation just write a partial class). Something like the following:
public partial class MyEntityContext
{
public override int SaveChanges(SaveOptions options)
{
IEnumerable<ObjectStateEntry> changedEntities =
this.ObjectStateManager.GetObjectStateEntries(
System.Data.EntityState.Added | System.Data.EntityState.Modified);
// here you can loop over your added/changed entities and
// process the custom attributes that you have
return base.SaveChanges(options);
}
}