I have the following class:
public class Account
{
public int AccountID { get; set; }
public Enterprise Enterprise { get; set; }
public List<User> UserList { get; set; }
}
And I have the following method fragment:
Entities.Account accountDto = new Entities.Account();
DAL.Entities.Account account;
Mapper.CreateMap<DAL.Entities.Account, Entities.Account>();
Mapper.CreateMap<DAL.Entities.User, Entities.User>();
account = DAL.Account.GetByPrimaryKey(this.Database, primaryKey, withChildren);
Mapper.Map(account,accountDto);
return accountDto;
When the method is called, the Account class gets mapped correctly but the list of users in the Account class does not (it is NULL). There are four User entities in the List that should get mapped. Could someone tell me what might be wrong?
Try not passing in the accountDto, and let AutoMapper create it for you. When you map to an existing destination object, AutoMapper makes a few assumptions, that you won't have any already-null destination collections for one. Instead, do:
var accountDto = Mapper.Map<DAL.Entities.Account, Entities.Account>(account);
The last thing you should check is that your configuration is valid, so you can try:
Mapper.AssertConfigurationIsValid();
After those CreateMap calls. This checks to make sure everything lines up properly on the destination type side of things.
Related
What I'm trying to achieve here is to save the current user instance in my ApiConfigurationRecord table. I already dig around the internet, and most of the example is using UserPartRecord. But the troble I encounter is to get the UserPartRecord object itself.
This is my Entity class look like:
public class ApiConfigurationRecord
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual UserPartRecord RegisterBy { get; set; }
}
This is my Migration.cs code look like:
public int Create()
{
SchemaBuilder.CreateTable("ApiConfigurationRecord", table => table
.Column<int>("Id", column => column.PrimaryKey().Identity())
.Column<int>("RegisterBy_id")
.Column<string>("Name", column => column.NotNull())
);
return 1;
}
This is my Action Controller codes:
public ActionResult Test()
{
var userId = this._orchardServices.WorkContext.CurrentUser.Id;
// below code got error: The non-generic method IContentManager.Query() cannot be used with type arguments
this._orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.Id == userId);
return null;
}
For hours I stuck in this problem. Need to know how to save this User relationship object, and most importantly, get the object itself. Please guide me.
Or you could just do
_orchardServices.WorkContext.CurrentUser.As<UserPart>().Record;
Though you will probably want to check user is not null there too. And as Bertrand Le Roy says, you will also need
using Orchard.ContentManagement;
to make use of the .As extension method.
My super-powers tell me that you are missing the following on top of your controller file:
using Orchard.ContentManagement;
The generic version of the Query method is an extension method that is in this namespace.
here are my entities:
public abstract class ResourceBase
{
[Key]
int Id { get; set; }
[ForeignKey("Resource")]
public Guid ResourceId { get; set; }
public virtual Resource Resource { get; set; }
}
public class Resource
{
[Key]
public Guid Id { get; set; }
public string Type { get; set; }
}
public class Message : ResourceBase
{
[MaxLength(300)]
public string Text { get; set; }
}
And then my query is something like this:
var msgs = messages.Where(x=>x.Id == someRangeOfIds).Include(m=>m.Resource).Select(x => new
{
message = x,
replyCount = msgs.Count(msg => msg.Id = magicNumber)
});
I am running this with proxy creation disabled, and the result is all the messages BUT with all the Resource properties as NULL. I checked the database and the Resources with matching Guids are there.
I drastically simplified my real life scenario for illustration purposes, but I think you'll find you can reproduce the issue with just this.
Entity Framework 5 handles inherited properties well (by flattening the inheritence tree and including all the properties as columns for the entity table).
The reason this query didn't work was due to the projection after the include. Unfortunately, the include statement only really works when you are returning entities. Although, I did see mention of a solution which is tricky and involves invoking the "include" after the shape of the return data is specified... If anyone has more information on this please reply.
The solution I came up with was to just rephrase the query so I get all messages in one query, and then in another trip to the database another query that gets all the reply counts.
2 round trips when it really should only be 1.
I have an aggregate named Campaigns every with a root entity named campaign, this root entity has a list of attempts (entity)
public class Attempts: IEntity<Attempts>
{
private int id;
public AttempNumber AttemptNumber {get;}
//other fields
}
public class Campaign: IEntity<Campaign> //root
{
private int id;
public IList<Attempt> {get;}
//other fields
}
Im using a method to add a campaign attempt
public virtual void AssignAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
this.attempts.add(att);
}
Problem comes when i try to edit a specific item in attempts list. I get Attempt by AttempNumber and pass it to editAttempt method but i dont know how to set the attempt without deleting whole list and recreate it again
public virtual void EditAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
}
Any help will be appreciated!
Thanks,
Pedro de la Cruz
First, I think there may be a slight problem with your domain model. It seems to me like 'Campaign' should be an aggregate root entity having a collection of 'Attempt' value objects (or entities). There is no 'Campaigns' aggregate unless you have a parent concept to a campaign which would contain a collection of campaigns. Also, there is no 'Attempts' entity. Instead a collection of 'Attempt' entities or values on the 'Campaign' entity. 'Attempt' may be an entity if it has identity outside of a 'Campaign', otherwise it is a value object. The code could be something like this:
class Campaign {
public string Id { get; set; }
public ICollection<Attempt> Attempts { get; private set; }
public Attempt GetAttempt(string id) {
return this.Attempts.FirstOrDefault(x => x.Number == id);
}
}
class Attempt {
public string Number { get; set; }
public string Attribute1 { get; set; }
}
If you retrieve an Attempt from the Campaign entity and then change some of the properties, you should not have to insert it back into the campaign entity, it is already there. This is how the code would look if you were using NHibernate (similar for other ORMs):
var campaign = this.Session.Get<Campaign>("some-id");
var attempt = campaign.GetAttempt("some-attempt-id");
attempt.Attribute1 = "some new value";
this.Session.Flush(); // will commit changes made to Attempt
You don't need an Edit method. Your code can modify the Attempts in-place, like so:
Attempt toModify = MyRepository.GetAttemptById(id);
toModify.Counter++;
toModify.Location = "Paris";
MyRepository.SaveChanges(); // to actually persist to the DB
Of course how you name the SaveChanges() is up to you, this is the way Entity Framework names its general Save method.
Say I have this class:
public class Account
{
public int AccountID { get; set; }
public Enterprise Enterprise { get; set; }
public List<User> UserList { get; set; }
}
When I use AutoMapper to map the Account class, I would also like it to map the Enterprise class, and the list of users (UserList) in the returned object. How can I get AutoMapper to do this?
Thanks!
AutoMapper does that out of-the-box if you provide a configuration for the Enterprise and User type.
Configuration looks like this:
Mapper.CreateMap<Account, AccountDto>();
Mapper.CreateMap<Enterprise, EnterpriseDto>();
Mapper.CreateMap<User, UserDto>();
This shows how to how collections get mapped:
http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays&referringTitle=Home
You need to create a mapping for each pair of types you would like mapped.
Mapper.CreateMap<Account, AccountDto>();
Mapper.CreateMap<Enterprise, EnterpriseDto>();
Mapper.CreateMap<User, UserDto>();
Order is not important.
I'm attempting to use the SimpleRepository to perform a fetch based on a non-ID property. Here's the Customer class I'm using:
[Serializable]
public class Customer : IEntity<Guid>
{
public Guid ProviderUserKey { get; set; }
public Guid ID
{
get; set;
}
}
I'm using SimpleRepository with migrations turned on. The code that throws the "Lambda Parameter not in scope" is below:
public class CustomerRepository :
ICustomerRepository
{
private readonly IRepository _impl;
public CustomerRepository(string connectionStringName)
{
_impl = new SimpleRepository(connectionStringName,
SimpleRepositoryOptions.RunMigrations);
}
public Customer GetCustomer(string userName)
{
var user = Membership.GetUser(userName);
// Code to guard against a missing user would go here
// This line throws the exception
var customer = _impl.Single<Customer>(c => c.ProviderUserKey.Equals(user.ProviderUserKey));
// Code to create a new customer based on the
// ASP.NET Membership user would go here
return customer;
}
}
I'm not sure at what point in the LINQ expression compilation this throws, but I am running this example on an empty database. The schema generations gets far enough to create the table structure, but can't evaluate the expression.
Does anyone know what I might be doing wrong?
Thanks!
I've had reports of this - can you add this (and your code) as an issue please?