Missing type map configuration or unsupported mapping.while trying to assign the data to DTO object - asp.net-core-3.1

I am using AutoMapper.Extensions.Microsoft.DependencyInjection. I am using the Automapper NuGet package: AutoMapper.Extensions.Microsoft.DependencyInjection (7.0.0) for ASP.NET Core 3.1 application.
Here goes my domain object: file ResourceGroup.cs
public class ResourceGroups
{
public string id
{
get;
set;
}
public int ResourceGroupId
{
get;
set;
}
public bool IsPublished
{
get;
set;
}
public int? Position
{
get;
set;
}
public string CreatedBy
{
get;
set;
}
public string CreatedDate
{
get;
set;
}
public string UpdatedBy
{
get;
set;
}
public string UpdatedDate
{
get;
set;
}
public int? ResourceGroupContentId
{
get;
set;
}
public int LanguageId
{
get;
set;
}
public string GroupName
{
get;
set;
}
}
Here goes my DTO object: file ResourceGroupDTO.cs
public class ResourceGroupDTO
{
public int ResourceGroupId
{
get;
set;
}
public int? Position
{
get;
set;
}
[JsonProperty("groupname")]
[RegularExpression(Constants.GeneralStringRegularExpression)]
public string GroupName
{
get;
set;
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
}
);
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
}
MappingProfile.cs
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ResourceGroups, ResourceGroupDTO>();
CreateMap<List<ResourceGroups>, List<ResourceGroupDTO>>();
}
}
file ResourceGroupService.cs
public class ResourceGroupService : IResourceGroupService
{
private readonly DemoDbContext _dbContext;
private readonly ICommonService _commonService;
private readonly IMapper _mapper;
public ResourceGroupService(DemoDbContext dbContext, ICommonService commonService, IMapper mapper)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
_commonService = commonService ?? throw new ArgumentNullException(nameof(commonService));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public async Task<ResourceGroupDTO> GetResourceGroupDetailsAsync(int resourceGroupId, int languageId)
{
var resourceGroup = await _dbContext.ResourceGroups.Where(rg => rg.ResourceGroupId.Equals(resourceGroupId) && rg.IsPublished.Equals(true))
.Select(rg => new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId })
.AsNoTracking().ToListAsync();
var resGroup = resourceGroup.FirstOrDefault(rg => rg.LanguageId.Equals(languageId));
return _mapper.Map<ResourceGroupDTO>(resGroup);
}
}
While debugging the above code I get the below error:
Missing type map configuration or unsupported mapping. \n \nMapping types : \
n<> f__AnonymousType4 ` 4 ->
ResourceGroupDTO \n<> f__AnonymousType4 ` 4
[
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ,
[System.Nullable ` 1[
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ] ,
System.Private.CoreLib , Version = 4.0 .0 .0 , Culture = neutral , PublicKeyToken = 7 cec85d7bea7798e ] , [System.String, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ,
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ] ->
Author.Query.Persistence.DTO.ResourceGroupDTO \n -- ->AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping. \n \nMapping types : \
n<> f__AnonymousType4 ` 4 ->

You're trying to map an anonymous type, i.e.
new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId }
onto a ResourceGroupDTO, hence the error.
To quickly fix your error you could just change the above to
new ResourceGroupDTO { ResourceGroupId = rg.ResourceGroupId, Position = rg.Position, GroupName = rg.GroupName, LanguageId = rg.LanguageId }
and then add LanguageId to ResourceGroupDTO and get rid of the mapper.
But what you should really be using is ProjectTo and you should change your .FirstOrDefault to a .Where - to make your query more efficient, in the format shown below:
await _dbContext.ResourceGroups
.AsNoTracking()
.Where(/* Put your where here */)
.ProjectTo<ResourceGroupDTO>(_mapper.Configuration)
.FirstOrDefaultAsync();
You can also simplify your startup

Related

.NET Core MongoDB. Find by guid returns null

I have the following setup:
The document:
[BsonCollection("Users")] // I get the collection name with a custom extension
[BsonIgnoreExtraElements]
public class UserDocument
{
[BsonId]
public Guid Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public UserSettingsModel UserSettings { get; set; }
}
public class UserSettingsModel
{
// ...
}
The repository:
public class UserRepository
{
private readonly IMongoCollection<UserDocument> _collection;
private readonly ILogger<UserRepository> _logger;
public UserRepository(IMongoDatabase database, ILogger<UserRepository> logger)
{
// returns "Users"
var collectionName = typeof(UserDocument).GetCollectionName();
_collection = database.GetCollection<UserDocument>(collectionName);
}
// ...
public async Task<UserDocument> GetById(Guid id)
{
var filter = Builders<UserDocument>.Filter.Eq(x => x.Id, id);
var user = await _collection.FindAsync(filter);
// var user = await _collection.FindAsync(x => x.Id == id); - doesn't work either
var request = filter.Render(
_collection.DocumentSerializer,
_collection.Settings.SerializerRegistry).ToString();
_logger.LogDebug(request);
return user.FirstOrDefault();
}
}
And I initialize the client this way:
// ...
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
var client = new MongoClient(connectionString);
var database = client.GetDatabase(dbName);
services.AddSingleton(c => database);
// convention pack and registries
// ...
// if moved here doesn't work either
// BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
The filter generated in GetById is still the following: { "_id" : CSUUID("459f165a-4a91-4f39-906c-dc7401ee2468") } when I expect it to be UUID instead of CSUUID.
So, the query doesn't find anything and returns null. In the database the document I'm searching for has _id: UUID('459f165a-4a91-4f39-906c-dc7401ee2468')
What am I doing wrong?
I was able to fixing by this trick:
var mongoConnectionUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoConnectionUrl);
// before initializing client
mongoClientSettings.GuidRepresentation = GuidRepresentation.Standard;
However setting the GuidRepresentation in client settings is obsolete, which is quite confusing. Also, the query generated still has CSUUID instead of UUID. I was able to log the query the following way:
mongoClientSettings.ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(e => logger.LogDebug($"{e.CommandName} - {e.Command.ToJson()}"));
};
If anyone finds a better way and post it here it would be appreciated.

Update Navigation Property with Entity.CurrentValues.SetValues

I have a Kalem Entity with a collection of DigerKalemMaliyetleri property, which is a collection of MaliyetBirimi objects. DigerKalemMaliyetleri is of JSON type and stored at the same table as a JSON column.
public class Kalem
{
public int Id { get; set; }
[Column(TypeName = "json")]
public ICollection<MaliyetBirimi> DigerKalemMaliyetleri { get; set; }
}
public class MaliyetBirimi
{
public int? DovizCinsi { get; set; }
public decimal? Maliyet { get; set; }
}
When I try to update entity with only DigerKalemMaliyetleri property changed:
DataContext.Entry<Kalem>(first).CurrentValues.SetValues(second);
SQL Update command isn't executed and database record is not updated.
How could I update the entity without explicitly setting DigerKalemMaliyetleri property?
Regards
I had the same problem, you cann't actually use SetValues to update navigation property, you nead instead use DataContext.Update(YourNewObj) and then DataContext.SaveChanges();, or if you want to use SetValues approach, you need:
-Get the exist entry
Kalem existObj = DataContext.Kalems.Find(YourNewObj.Id);
-Loop in navigations of updating entry and the existing one to set the values of updating entry:
foreach(var navObj in DataContext.Entry(YourNewObj).Navigations)
{
foreach(var navExist in DatatContext.Entry(existObj).Navigations)
{
if(navObj.Metadata.Name == navExist.MetaData.Name)
navExist.CurrentValue = navObj.CurrentValue;
}
}
-Update also changes of direct properties:
DataContext.Entry(existObj).CurrentValues.SetValues(YourNewObj);
-Save your Updating:
DataContext.SaveChanges();
You can also check if you need to load your Navigations before going in foreach loop, otherwise you will get an error.
Please if you see beter scenario, correct me.
It's hard to know exactly what you're doing without a complete code sample. Note also that you're trying to set all properties of first from second, including e.g. the Id, which is probably not what you want.
Here's a complete code sample which works for me:
await using (var ctx = new BlogContext())
{
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
ctx.Kalem.Add(new()
{
DigerKalemMaliyetleri = new List<MaliyetBirimi>()
{
new() { DovizCinsi = 1, Maliyet = 2 }
}
});
await ctx.SaveChangesAsync();
}
await using (var ctx = new BlogContext())
{
var first = ctx.Kalem.Find(1);
var second = new Kalem
{
DigerKalemMaliyetleri = new List<MaliyetBirimi>()
{
new() { DovizCinsi = 3, Maliyet = 4 }
}
};
ctx.Entry(first).Property(k => k.DigerKalemMaliyetleri).CurrentValue = second.DigerKalemMaliyetleri;
await ctx.SaveChangesAsync();
}
public class BlogContext : DbContext
{
public DbSet<Kalem> Kalem { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(#"Host=localhost;Username=test;Password=test")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
}
public class Kalem
{
public int Id { get; set; }
[Column(TypeName = "json")]
public ICollection<MaliyetBirimi> DigerKalemMaliyetleri { get; set; }
}
public class MaliyetBirimi
{
public int? DovizCinsi { get; set; }
public decimal? Maliyet { get; set; }
}

Add include on DbContext level

I want to implement something similar to lazy loading, but don't understand how to implement that. I want to force entity framework core include navigation property for all queries for type which implements my interface
public interface IMustHaveOrganisation
{
Guid OrganisationId { get; set; }
Organisation Organisation { get; set; }
}
public class MyEntity : IMustHaveOrganisation {
public Guid OrganisationId { get; set; }
public virtual Organisation Organisation { get; set; }
}
Without lazy loading I need to add .Include(x=>x.Organisation) to each query literally , and I can't use implementation of lazy loading provided by Microsoft. I need kind of custom implementation of that with loading just one property.
Or even force DbContext somehow to Include that property, it also fine for me.
How can I achieve that?
You can make this work by rewriting the expression tree, before it gets translated by EF Core.
To make this work in a way, where you don't have to specify anything additional in the query, you can hook into the very beginning of the query pipeline and inject the Include() call as needed.
This can be done, by specifying a custom IQueryTranslationPreprocessorFactory implementation.
The following fully working console project demonstrates this approach:
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
{
public class Organisation
{
public int OrganisationId { get; set; }
public string Name { get; set; }
}
public interface IMustHaveOrganisation
{
int OrganisationId { get; set; }
Organisation Organisation { get; set; }
}
public class MyEntity : IMustHaveOrganisation
{
public int MyEntityId { get; set; }
public string Name { get; set; }
public int OrganisationId { get; set; }
public virtual Organisation Organisation { get; set; }
}
public class CustomQueryTranslationPreprocessorFactory : IQueryTranslationPreprocessorFactory
{
private readonly QueryTranslationPreprocessorDependencies _dependencies;
private readonly RelationalQueryTranslationPreprocessorDependencies _relationalDependencies;
public CustomQueryTranslationPreprocessorFactory(
QueryTranslationPreprocessorDependencies dependencies,
RelationalQueryTranslationPreprocessorDependencies relationalDependencies)
{
_dependencies = dependencies;
_relationalDependencies = relationalDependencies;
}
public virtual QueryTranslationPreprocessor Create(QueryCompilationContext queryCompilationContext)
=> new CustomQueryTranslationPreprocessor(_dependencies, _relationalDependencies, queryCompilationContext);
}
public class CustomQueryTranslationPreprocessor : RelationalQueryTranslationPreprocessor
{
public CustomQueryTranslationPreprocessor(
QueryTranslationPreprocessorDependencies dependencies,
RelationalQueryTranslationPreprocessorDependencies relationalDependencies,
QueryCompilationContext queryCompilationContext)
: base(dependencies, relationalDependencies, queryCompilationContext)
{
}
public override Expression Process(Expression query)
{
query = new DependenciesIncludingExpressionVisitor().Visit(query);
return base.Process(query);
}
}
public class DependenciesIncludingExpressionVisitor : ExpressionVisitor
{
protected override Expression VisitConstant(ConstantExpression node)
{
// Call Include("Organisation"), if SomeEntity in a
// DbSet<SomeEntity> implements IMustHaveOrganisation.
if (node.Type.IsGenericType &&
node.Type.GetGenericTypeDefinition() == typeof(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<>) &&
node.Type.GenericTypeArguments.Length == 1 &&
typeof(IMustHaveOrganisation).IsAssignableFrom(node.Type.GenericTypeArguments[0]))
{
return Expression.Call(
typeof(EntityFrameworkQueryableExtensions),
nameof(EntityFrameworkQueryableExtensions.Include),
new[] {node.Type.GenericTypeArguments[0]},
base.VisitConstant(node),
Expression.Constant(nameof(IMustHaveOrganisation.Organisation)));
}
return base.VisitConstant(node);
}
}
public class Context : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
public DbSet<Organisation> Organisations { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Register the custom IQueryTranslationPreprocessorFactory implementation.
// Since this is a console program, we need to create our own
// ServiceCollection for this.
// In an ASP.NET Core application, the AddSingleton call can just be added to
// the general service configuration method.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlServer()
.AddSingleton<IQueryTranslationPreprocessorFactory, CustomQueryTranslationPreprocessorFactory>()
.AddScoped(
s => LoggerFactory.Create(
b => b
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.BuildServiceProvider();
optionsBuilder
.UseInternalServiceProvider(serviceProvider) // <-- use our ServiceProvider
.UseSqlServer(#"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=62849896")
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>(
entity =>
{
entity.HasData(
new MyEntity {MyEntityId = 1, Name = "First Entity", OrganisationId = 1 },
new MyEntity {MyEntityId = 2, Name = "Second Entity", OrganisationId = 1 },
new MyEntity {MyEntityId = 3, Name = "Third Entity", OrganisationId = 2 });
});
modelBuilder.Entity<Organisation>(
entity =>
{
entity.HasData(
new Organisation {OrganisationId = 1, Name = "First Organisation"},
new Organisation {OrganisationId = 2, Name = "Second Organisation"});
});
}
}
internal static class Program
{
private static void Main()
{
using var context = new Context();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var myEntitiesWithOrganisations = context.MyEntities
.OrderBy(i => i.MyEntityId)
.ToList();
Debug.Assert(myEntitiesWithOrganisations.Count == 3);
Debug.Assert(myEntitiesWithOrganisations[0].Name == "First Entity");
Debug.Assert(myEntitiesWithOrganisations[0].Organisation.Name == "First Organisation");
}
}
}
Even though no explicit Include() is being made in the query in Main(), the following SQL is being generated, that does join and retrieve the Organisation entities:
SELECT [m].[MyEntityId], [m].[Name], [m].[OrganisationId], [o].[OrganisationId], [o].[Name]
FROM [MyEntities] AS [m]
INNER JOIN [Organisations] AS [o] ON [m].[OrganisationId] = [o].[OrganisationId]
ORDER BY [m].[MyEntityId]

Invalid date with BreezeJS and Hottowel

i've a problem whit breeze returned DateTime... i've tried also to update BreezeJs to the latest version but nothing change. I use breezeJs with HotTowel SPA
Controller:
[BreezeController]
public class ContribuentiController : ApiController
{
readonly EFContextProvider<LarksTribContext> _contextProvider =
new EFContextProvider<LarksTribContext>();
[System.Web.Http.HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
// ~/api/todos/Todos
// ~/api/todos/Todos?$filter=IsArchived eq false&$orderby=CreatedAt
[System.Web.Http.HttpGet]
public IQueryable<Contribuente> Contribuenti()
{
if (_contextProvider.Context.Contribuente != null)
{
return _contextProvider.Context.Contribuente.Include("Residenze.Strada");//.Include("Residenze").Include("Residenze.Strada");
}
else
{
return null;
}
}
[System.Web.Http.HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Model:
[Table(name: "Contribuenti")]
public class Contribuente
{
[Key]
public int Id { get; set; }
[MaxLength(30,ErrorMessage = "Il cognome non deve superare i 30 caratteri")]
public string Cognome { get; set; }
[MaxLength(35, ErrorMessage = "Il nome non deve superare i 35 caratteri")]
public string Nome { get; set; }
[MaxLength(16, ErrorMessage = "Il Codice fiscale non deve superare i 16 caratteri")]
public string CodiceFiscale { get; set; }
public virtual ICollection<Residenza> Residenze { get; set; }
}
[Table(name: "Residenze")]
public class Residenza
{
[Key, Column(Order = 0)]
public int Id { get; set; }
public int ContribuenteId { get; set; }
[ForeignKey("ContribuenteId")]
public Contribuente Contribuente { get; set; }
public DateTime? DataInizio { get; set; }
public int StradaId { get; set; }
[ForeignKey("StradaId")]
public Strada Strada { get; set; }
public int Civico { get; set; }
public string Interno { get; set; }
public string Lettera { get; set; }
}
[Table(name: "Strade")]
public class Strada
{
[Key]
public int Id { get; set; }
[MaxLength(20,ErrorMessage = "Il toponimo deve contenere al massimo 20 caratteri")]
public string Toponimo { get; set; }
[MaxLength(50, ErrorMessage = "Il nome deve contenere al massimo 50 caratteri")]
public string Nome { get; set; }
}
when i make this query:
var query = breeze.EntityQuery.
from("Contribuenti").expand(["Residenze"], ["Strada"]);
the json response is:
[{"$id":"1","$type":"LarksTribUnico.Models.Contribuente, LarksTribUnico","Id":1,"Cognome":"Manuele","Nome":"Pagliarani","CodiceFiscale":"HSDJSHDKHSD","Residenze":[{"$id":"2","$type":"LarksTribUnico.Models.Residenza, LarksTribUnico","Id":5,"ContribuenteId":1,"Contribuente":{"$ref":"1"},"DataInizio":"2012-12-10T22.00.00.000","StradaId":4,"Strada":{"$id":"3","$type":"LarksTribUnico.Models.Strada, LarksTribUnico","Id":4,"Toponimo":"Via","Nome":"Milano"},"Civico":0}]}]
But in result of query "DataInizio" is always marked as "Invalid date".
Any idea aout the problem?
Thanks
Breeze server side converts SQL Server DateTime to ISO 8601. In my code (breeze v0.72) dates seem to end up in UTC in SQL, and get converted back to local somewhere in breeze.
Check the Breeze docs on dates. http://www.breezejs.com/documentation/date-time
or, as suggested in the breeze docs, you can add moment.js to your project if HotTowel does not. https://github.com/moment/moment
Moment recognizes the JSON you are describing.
A moment() is different than a JavaScript date, but it is easier to manipulate and parse.
This code you the current browser date from moment.
var now = window.moment().toDate();
This code demonstrates how to turn an ISO into a JavaScript Date object through moment.
// ISO 8601 datetime returned in JSON.
// In your code, you would pull it out of your the
// return variable in your dataservice.js
var DataInizio = "2012-12-10T22.00.00.000"
// convert your variable to a moment so you can parse it
var momentdatainizio = window.moment(DataInizio);
// convert the ISO to a javascript Date object so you can use it in js.
var mydate = window.moment(DataInizio).toDate();
Your Stada will end up in the breeze Metadata store which you use to populate your viewModel.
Retrieve the strada from the Metadata store or the database with something like this code in your dataservice.js. I am being a little more verbose than necessary so you can debug.
var getStrada = function (stradaId, callback) {
var query = EntityQuery.from("Strada")
.using(manager);
var pred = new breeze.Predicate("idd", "eq", stradaId);
// create the query
var queryb = query.where(pred);
// check the MetadataStore to see if you already have it
var localsession = queryb.executeLocally();
if (localsession) {
if (localsession.length > {
window.app.vm.strada.strada(data.results);
return localsession;
}
}
// get it from the server
else {
// return the promise to prevent blocking
// then set your viewModel when the query fulfills
// then make your callback if there is one
// handle the fail in your queryFailed function if there is a problem
return manager.executeQuery(queryb)
.then(function (data) {
window.app.vm.strada.strada(data.results);
})
.then(function () {
if ((typeof callback !== 'undefined' && callback !== null)) {
callback();
}
})
.fail(function () {
queryFailed();
});
}
};
Here is a fragment of a ko viewModel in strada.js
app.vm.strada = (function ($, ko, dataservice, router) {
var strada = ko.observable();
...
return {
strada : strada,
...
})($, ko, app.dataservice, app.router);
Here is the custom binding handler for knockout in the ko.bindingHandlers.js. This code is slightly verbose so you can debug the intermediate variables.
window.ko.bindingHandlers.DataInizio = {
// viewModel is a Strada
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = window.ko.utils.unwrapObservable(value);
var $el = $(element);
if (valueUnwrapped.toString().indexOf('Jan 1') >= 0)
$el.text("Strada not Started");
else {
var date = new Date(valueUnwrapped);
var d = moment(date);
$el.text(d.format('MM/DD/YYYY'));
}
}
};
Here is the html for the binding handler
...
Strada DataInizio:
...
I wrote this code based upon my code using Breeze v0.72 which uses sammy.js as the router. Your mileage may vary with newer versions of breeze and Durandel.

Entity Framework , how to only validate specify property

I have a demo class "User" like the following:
public partial class User {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(30)]
[Required]
public string LoginName { get; set; }
[StringLength(120)]
[Required]
[DataType(DataType.Password)]
public string Pwd { get; set; }
[StringLength(50)]
public string Phone { get; set; }
[StringLength(100)]
public string WebSite { get; set; }
...
...
}
As you can see, "LoginName" and "Pwd" are "Required".
Some time , I only want to update user's "WebSite" , So I do like this:
public void UpdateUser(User user , params string[] properties) {
this.rep.DB.Users.Attach(user);
this.rep.DB.Configuration.ValidateOnSaveEnabled = false;
var entry = this.rep.DB.Entry(user);
foreach(var prop in properties) {
var entProp = entry.Property(prop);
//var vas = entProp.GetValidationErrors();
entProp.IsModified = true;
}
this.rep.DB.SaveChanges();
this.rep.DB.Configuration.ValidateOnSaveEnabled = true;
}
Parameter "user" like this:
new User(){
ID = 1,
WebSite = "http://www.stackoverflow.com"
}
Notice , I don't specify "LoginName" and "Pwd"
This function can work fine , but I wouldn't set ValidateOnSaveEnabled to false.
Is there any way only validate "WebSite" when ValidateOnSaveEnabled is true?
Thanks.
As I know validation executed in SaveChanges always validates the whole entity. The trick to get selective validation for property is commented in your code but it is not part of the SaveChanges operation.
I get a solution.
First define PartialValidationManager:
public class PartialValidationManager {
private IDictionary<DbEntityEntry , string[]> dics = new Dictionary<DbEntityEntry , string[]>();
public void Register(DbEntityEntry entry , string[] properties) {
if(dics.ContainsKey(entry)) {
dics[entry] = properties;
} else {
dics.Add(entry , properties);
}
}
public void Remove(DbEntityEntry entry) {
dics.Remove(entry);
}
public bool IsResponsibleFor(DbEntityEntry entry) {
return dics.ContainsKey(entry);
}
public void ValidateEntity(DbEntityValidationResult result) {
var entry = result.Entry;
foreach(var prop in dics[entry]){
var errs = entry.Property(prop).GetValidationErrors();
foreach(var err in errs) {
result.ValidationErrors.Add(err);
}
}
}
}
2, Add this Manager to My DbContext:
public class XmjDB : DbContext {
public Lazy<PartialValidationManager> PartialValidation = new Lazy<PartialValidationManager>();
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry , IDictionary<object , object> items) {
if(this.PartialValidation.Value.IsResponsibleFor(entityEntry)) {
var result = new DbEntityValidationResult(entityEntry , new List<DbValidationError>());
this.PartialValidation.Value.ValidateEntity(result);
return result;
} else
return base.ValidateEntity(entityEntry , items);
}
...
...
Update Method :
public void UpateSpecifyProperties(T t, params string[] properties) {
this.DB.Set<T>().Attach(t);
var entry = this.DB.Entry<T>(t);
this.DB.PartialValidation.Value.Register(entry , properties);
foreach(var prop in properties) {
entry.Property(prop).IsModified = true;
}
this.DB.SaveChanges();
this.DB.PartialValidation.Value.Remove(entry);
}
Ok, it work fine.