Castle Activerecord. Two collections of the same class - castle-activerecord

I want to have two collections of same class items in Activerecord.
How to map this?
class Project
{
[HasMany]
IList<Resource> Resources { get; set; }
[HasMany]
IList<Resource> DepartmentResources { get; set; }
}
public class Resource
{
[BelongsTo ???
}

Use the ColumnKey property, e.g.:
[HasMany(ColumnKey="res")]
IList<Resource> Resources { get; set; }
[HasMany(ColumnKey="deptres")]
IList<Resource> DepartmentResources { get; set; }
...
public class Resource {
[BelongsTo("res")]
Project Project {get;set;}
[BelongsTo("deptres")]
Project DeptProject {get;set;}
}

Related

AutoMapper with Array and JsonApiSerializer.JsonApi.Relationship

I have an AppService solution with the following Classes and i want to map from the SourceObject to the DestinationObject
Source Classes
public class SourceObject
{
public string Id { get; set; }
public string Name { get; set; }
public JsonApiSerializer.JsonApi.Relationship<SourceChildObject[]> childObjects { get; set; }
}
public class SourceChildObject
{
public string Id { get; set; }
public string type { get; set; }
}
Destination Classes
public class DestinationObject
{
public string Id { get; set; }
public string Name { get; set; }
public JsonApiSerializer.JsonApi.Relationship<DestinationChildObject[]> childObjects { get; set; }
}
public class DestinationChildObject
{
public string Id { get; set; }
public string type { get; set; }
}
Auto mapper is setup in the sartup class
services.AddAutoMapper(typeof(EntityMappingProfile));
And my mapping class loos like this
public class EntityMappingProfile : Profile
{
public EntityMappingProfile()
{
CreateMap<SourceObject, DestinationObject>();
CreateMap<Relationship<SourceChildObject[]>, Relationship<DestinationChildObject[]>>();
}
}
When i execute the solution all fields are mapped apart form the array field of type JsonApiSerializer.JsonApi.Relationship. The destination field is null. What am i doing wrong?
You forgot about creating a map between SourceChildObject and DestinationChildObject. Add this line to your EntityMappingProfile.
CreateMap<SourceChildObject, DestinationChildObject>();
And one more thing, when you are mapping generic types, you can enable mapping for all types with:
CreateMap(typeof(Relationship<>), typeof(Relationship<>));
instead of creating a map with concrete use case of a generic type.

Entity Framework Core - How to include/populate a navigation property with custom(1-to-1) query in EF?

How to include/populate a navigation property with custom(1-to-1) query in EF?
e.g.
public class Item {
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Id")]
public ItemCost LatestCost {get; set; }
}
public class ItemCost {
public int Id { get; set; }
public DateTime From { get; set; }
public DateTime? To { get; set; }
public decimal Cost { get; set; }
}
Goal is to populate the LatestCost property of the Item with it's latest cost from ItemCosts. How is this being accomplished with EF or what's your take on this?
Is it possible to do a custom query within .Include/.ThenInclude methods?
e.g.
.ThenInclude(a => { a.LatestCost = (from a _db.ItemCosts
where... select a).SingleOrDefault() })...
You could use a virtual get-only property. Your nav property should really be an ICollection<ItemCost>. In this example I'm assuming the Id property in the ItemCost class is the id of the related Item, but it's not clear. Tip: using nameof(property) instead of hard-coding the property name will allow the compiler to catch errors with the name if you were to change it for some reason. The [NotMapped] attribute tells Entity Framework to not try and map the property to a database field.
public class Item {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ItemCost> ItemCosts {get; set; }
[NotMapped]
public virtual ItemCost LatestCost
{
get
{
return ItemCosts.OrderByDescending(x => x.From).FirstOrDefault();
}
}
}
public class ItemCost {
public int Id { get; set; }
public DateTime From { get; set; }
public DateTime? To { get; set; }
public decimal Cost { get; set; }
[ForeignKey(nameof(Id))]
public virtual Item Item { get; set; }
}

Manual Changes to Entity Framework Database causes error

I am fairly new to Entity Framework and C#, so I apologize if my ability to describe the problem is minimal.
I have a .NET Web Forms project hosted on Azure that uses Entity Framework to handle all the database tables. I recently had an issue that I was debugging and I created test records, which I removed once the issue was solved using Microsoft SQL Server Management Studio. Unfortunately, I now get the following error:
"The model backing the 'RegSysContext' context has changed since the database was created. Consider using Code First Migrations to update the database"
The RegSysContext class can be seen below.
From what I understand, this is caused by the metadata that Entity Framework uses not matching the database anymore. The data in the database is essential to keep, otherwise I would just wipe it and forget about it.
How can I solve this issue on the hosted web app, and how can I edit the database in the future without causing this problem?
Thanks in advance!
public class RegSysContext : DbContext
{
// Default Constructor for the context class
public RegSysContext() : base("RegSys")
{
}
// Properties of the context class
public DbSet<CustomerAccountMembership> AccountMembershipRecords { get; set; }
// For Organization Account functionality
public DbSet<RegSysAccount> RegSysAccounts { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
public DbSet<SubscriptionRecord> SubscriptionRecords { get; set; }
public DbSet<PaymentInfo> PaymentAccountInfoRecords { get; set; }
// For Auction functionality
public DbSet<Auction> auctions { get; set; }
public DbSet<AuctionItem> auctionItems { get; set; }
public DbSet<AuctionLot> auctionLots { get; set; }
public DbSet<AuctionDonation> auctionDontations { get; set; }
public DbSet<AuctionSale> auctionSales { get; set; }
public DbSet<ItemInAuctionRecord> itemInAuctionRecords { get; set; }
// For Event functionality
public DbSet<Event> events { get; set; }
public DbSet<EventParticipant> eventParticipants { get; set; }
public DbSet<RegistrationPeriod> registrationPeriods { get; set; }
public DbSet<RegType> regTypes { get; set; }
public DbSet<RegPrice> regPrices { get; set; }
public DbSet<EventCategory> EventCategories { get; set; }
//public DbSet<RegistrationConfig> regConfigs { get; set; }
//public DbSet<RegFormConfig> regFormConfigs { get; set; }
// For Organization functionality
public DbSet<Lodge> Lodges { get; set; }
// For Participant functionality
public DbSet<Participant> Participants { get; set; }
public DbSet<Charge> Charges { get; set; }
public DbSet<EventParticipantToParticipantLinker> EventParticipantLinks { get; set; }
// For System functionality
public DbSet<RegSysMessage> RegSysMessages { get; set; }
public DbSet<Transaction> Transactions { get; set; }
// For Trading Post functionality
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<CartItem> ShoppingCartItems { get; set; }
public DbSet<ProductInventory> ProductInventories { get; set; }
public DbSet<TradingPost> TradingPosts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<ProductSale> ProductSales { get; set; }
public DbSet<SpecialOffer> SpecialOffers { get; set; }
}
Add this line to your constructor inside your RegSysContext class :
Database.SetInitializer<RegSysContext>(null);
What this line of code does it tells Entity Framework whether or not to create the database. Passing null into the IDatabaseInitializer strategy parameter, you basically disable the initialization of the database altogether (since it already exists)

RIA Services: Entities with child entities

Is it possible to have child objects on RIA Services entities that are also entities themselves?
public class Project
{
[Key]
public int ID { get; set; }
[Editable(false)]
public String Name { get; set; }
public Machine Machine { get; set; }
}
public class Machine
{
[Key]
public int ID { get; set; }
[Editable(false)]
public String Name { get; set; }
}
You can specify the [Include] attribute on the Machineproperty in the metadata class and add a call to Include("Machine") on the object context query.
See: http://vincenthomedev.wordpress.com/2010/01/08/using-wcf-ria-services-to-include-multi-table-master-detail-data/
I don't think so, at least not in the traditional sense.

Dealing with POCO in MVVM

I'm migrating from WinForms world to WPF with MVVM.
My base system works with POCO classes (NHibernate) and we use some DynamicProxy to map this POCO classes into some bindable so the ModelView can expose a proxy of POCO and save a lot of code:
public class OrderViewModel
{
public OrderPOCO Order { get; private set; }
}
public class OrderView
{
public OrderView()
{
DataContext = DynamicProxy(new OrderViewModel(new OrderPOCO()));
}
}
public class OrderPOCO
{
public virtual int Number { get; set; };
public virtual IList<OrderItemPOCO> Items { get; set; };
}
public class OrderItemPOCO
{
public virtual decimal Qty { get; set; }
public virtual decimal Price { get; set; }
public virtual decimal Amount { get; set; }
}
The collection of OrderItemPOCO is binded into a grid. The Amount is a calculated property that depends of some complex rules (I can't put it in the POCO as it's not a simple Amount = Qty * Price).
Sure I can expose in the ViewModel a custom OrderItemViewModel and a collection of OrderItemViewModel but I will need to recode my POCO classes. How I can code this kind of situation in MVVM without recode all my Model?
You are right, you need an OrderItemViewModel. But you don't have to rewrite you model classes, it will remain the same. What you need is something like this:
public class OrderViewModel
{
public OrderViewModel(OrderPOCO order)
{
Order = order;
Items = new ObservableCollection<OrderItemViewModel>(order.Items.Select(o => new OrderItemViewModel(o)).ToArray());
Items.CollectionChanged += OnItemsCollectionChanged;
}
public OrderPOCO Order { get; private set; }
public ObservableCollection<OrderItemViewModel> Items { get; private set; }
private void OnItemsCollectionChanged(object sender, CollectionChangedEventArgs e)
{
// Synchronize this.Items with order.Items
}
}
public class OrderItemViewModel
{
public OrderItemPOCO OrderItem { get; private set; }
}
public class OrderPOCO
{
public virtual int Number { get; set; };
public virtual IList<OrderItemPOCO> Items { get; set; };
}
public class OrderItemPOCO
{
public virtual decimal Qty { get; set; }
public virtual decimal Price { get; set; }
public virtual decimal Amount { get; set; }
}

Resources