Suppose you have a collection of collection
Eg : CEO-> Vps-> GMs ->..
CEO will contain collection of VP's, VP's will have collection of GM's and so on.
Suppose you need to find a particular GM is the alias is given. Write a linq query to get the employee details if the employee alias is given.
You could try something like below
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
CeoCollection myCEOs = new CeoCollection();
var myGM = myCEOs.SelectMany(a => a.DummyVps.SelectMany(b => b.DummyGms.FindAll(c => c.Alias == "VeryDumb")));
}
}
public abstract class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Alias { get; set; }
}
public class CeoCollection : List<Ceo> { }
public class Ceo : Employee
{
public VpCollection DummyVps { get; set; }
}
public class VpCollection : List<Vp> { }
public class Vp : Employee
{
public GmCollection DummyGms { get; set; }
}
public class GmCollection : List<Gm> { }
public class Gm : Employee
{
}
}
Related
My class have a list of another class.
public class CustomerRequest : BaseEntity
{
[Key]
public int Id { get; set; }
public int Code { get; set; }
public virtual List<TechnicalOfficer> TechnicalOfficers { get; set; }
}
public class TechnicalOfficers : BaseEntity
{
[Key]
public int Id { get; set; }
public int Code { get; set; }
}
I want to select all CustomerRequest that TechnicalOfficers are contains special id.
I want to select all CustomerRequest that TechnicalOfficers are contains special id.
Use Any (or perhaps All) with Contains.
var specialIds = new[] { 1, 2, 3 };
var customerRequests = CustomerRequests
.Where(cr => cr.TechnicalOfficers.Any(to => specialIds.Contains(to.Id)));
Can anyone tell me what kind of error is this?
The specified type member 'OrderDetails' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
What's wrong here in this code?
return storeDB.Albums.OrderByDescending(a=>a.OrderDetails.Count()).Take(count).ToList()
Since you are using EF code first try to add a configuration class to map the one to many relationship between Album and OrderDetails. The following will be a sample configuration for the Album.
public class AlbumConfiguration : EntityTypeConfiguration<Album>
{
public AlbumConfiguration()
{
HasKey(a => a.Id);
HasMany(album => album.Orders).WithOptional(order => order.Album).
HasForeignKey(order => order.AlbumId);
}
}
and your OrderDetails should be changed as follows
OrderDetail
{
public int OrderDetailId { get; set; }
public int OrderId { get; set; }
public int AlbumId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public virtual Album Album { get; set; }
public virtual Order Order { get; set; }
}
and your Album class should have a virtual List of OrderDetails.
and finally in your DbContext class add the configuration by overrinding the OnModelCreating method. sample class would be
public class YourContext : DbContext
{
// your DBSets and contructors, etc
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AlbumConfiguration());
base.OnModelCreating(modelBuilder);
}
}
Try this may be this is the cause of your exception
I want to create categories for news. It will be many-to-many relation. How do that properly? I have created two classes:
public class News
{
public News()
{
this.NewsCategories = new List<NewsCategory>();
}
public int ID { get; set; }
public DateTime Date { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public IEnumerable<NewsCategory> NewsCategories { get; set; }
}
public class NewsCategory
{
public NewsCategory()
{
this.News = new List<News>();
}
public int ID { get; set; }
public string Name { get; set; }
public IEnumerable<News> News { get; set; }
}
But EF create just two tables...without Join table. I have created also custom DbInitializer:
public class TouristGuideDBInitializer : DropCreateDatabaseAlways<TouristGuideDB>
{
protected override void Seed(TouristGuideDB context)
{
base.Seed(context);
context.NewsCategories.Add(new NewsCategory { Name = "Default" });
context.NewsCategories.Add(new NewsCategory { Name = "Second" });
context.News.Add(new News { Date = DateTime.Now, Text = "asasdfas fasdfa sdf asf asf", Title = "Hello world" });
context.SaveChanges();
var news = context.News.First();
var cat = context.NewsCategories.Where(r => r.Name == "Default").Single();
news.NewsCategories.ToList().Add(cat);
context.SaveChanges();
}
}
But it just add one news and two categories...without relationships...
How it should be done properly (the relations)?
You need to use ICollection<T> for navigation properties.
Given the classes:
public class Person
{
public string Name { get; set; }
}
public class Student : Person
{
public int StudentId { get; set; }
}
public class Source
{
public Person Person { get; set; }
}
public class Dest
{
public string PersonName { get; set; }
public int? PersonStudentId { get; set; }
}
I want to use Automapper to map Source -> Dest.
This test obviously fails:
Mapper.CreateMap<Source, Dest>();
var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }};
var dest = Mapper.Map<Source, Dest>(source);
Assert.AreEqual(5, dest.PersonStudentId);
What would be the best approach to mapping this given that "Person" is actually a heavily used data-type throughout our domain model.
Edit: The intent is to persist the "Dest" objects which will have fields defined for all properties of the sub-types of "Person". Hence we could have source objects like the following and would prefer not to have to create Dest objects for every possible combination of "Person" sub-classes:
public class Source2
{
public Person Value1 { get; set; }
public Person Value2 { get; set; }
public Person Value3 { get; set; }
public Person Value4 { get; set; }
public Person Value5 { get; set; }
}
Well using Jimmy's suggestion I've settled on the following solution:
public class Person
{
public string Name { get; set; }
}
public class Student : Person
{
public int StudentId { get; set; }
}
//all subtypes of person will map to this dto
public class PersonDto
{
public string Name { get; set; }
public int? StudentId { get; set; }
}
public class Source
{
public Person Person { get; set; }
}
public class DestDto
{
public PersonDto Person { get; set; }
}
public class Dest
{
public string PersonName { get; set; }
public int? PersonStudentId { get; set; }
}
[TestFixture]
public class RandomTests
{
[Test]
public void Test1()
{
Mapper.CreateMap<Person, PersonDto>();
Mapper.CreateMap<Student, PersonDto>();
Mapper.CreateMap<Source, DestDto>();
Mapper.CreateMap<DestDto, Dest>();
var source = new Source() { Person = new Student() { Name = "J", StudentId = 5 } };
var destDto = Mapper.Map<Source, DestDto>(source);
var destFinal = Mapper.Map<DestDto, Dest>(destDto);
Assert.AreEqual(5, destFinal.PersonStudentId);
}
}
Would love to hear suggestions/improvements.
I'm trying to get a web app working based on the S#arp Architecture. At the moment I have a the below code for my entity.
[Serializable]
public abstract class EventBase : Entity
{
#region Properties
[DomainSignature]
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual AgeRange Ages { get; set; }
public virtual int Rating { get; set; }
public virtual decimal Price { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string Website { get; set; }
public virtual EventState State { get; set; }
#endregion
protected EventBase() {}
protected EventBase(string name, string description)
{
// ReSharper disable DoNotCallOverridableMethodsInConstructor
Name = name;
Description = description;
Price = 0;
State = EventState.New;
// ReSharper restore DoNotCallOverridableMethodsInConstructor
}
}
This is mapped using Fluent NHibernate as follows
public class EventBaseMap : AutoMap<EventBase>
{
public EventBaseMap()
{
Id(x => x.ID).WithUnsavedValue(-1).GeneratedBy.Identity();
Component<AgeRange>(x => x.Ages, m =>
{
m.Map(x => x.From).TheColumnNameIs("AgeFrom");
m.Map(x => x.To).TheColumnNameIs("AgeTo");
});
JoinedSubClass<Music>("EventId", sub =>
{
sub.Map(x => x.Headliner);
});
}
}
I created a very simple repository using the very useful S#arp base repository classes.
public interface IEventRepository : INHibernateRepositoryWithTypedId<EventBase, int>
{
List<EventBase> FindByName(string searchPhase);
}
public class EventRepository : NHibernateRepository<EventBase>, IEventRepository
{
public List<EventBase> FindByName(string searchPhase)
{
return Session.Linq<EventBase>().Where(x => x.Name == searchPhase).ToList();
}
}
I can create entities in the db and return all records. When I try to test the FindByName method I get the below error.
NHibernate.QueryException: could not
resolve property: Name of:
Model.Events.EventBase
Does anyone have any ideas? Is it a problem with my mapping?
Thanks,
This is using the Auto-mapping feature. I thought you only explicitly map properties that you want to override or that don't meet the conventions?
If I add an explicit mapping this solves the issue but I am still not sure why.