I have an entity and I'm trying to add it to a collection in two different entities.
What I want to achieve is something like
[1] => DomainUser { name = "bob" }
DomainGroup.Users = [ 1 ]
LocalGroup.Users = [ 1 ]
When I try to save changes, however, I get Multiplicity constraint violated. The role 'DomainGroup_Users_Source' of the relationship 'Server.DomainTools.Models.DomainGroup_Users' has multiplicity 1 or 0..1.
Here's my entities:
This is where I feel my issues lies: DomainUser
public class DomainUser
{
public string Name { get; set; }
public int Id { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public int AdminCount { get; set; }
public int PwdLastSet { get; set; }
public string AdsPath { get; set; }
public int LastLogon { get; set; }
public int LastLogoff { get; set; }
public int LockoutTime { get; set; }
public int AccountExpires { get; set; }
public int BadPwdCount { get; set; }
public int LogonCount { get; set; }
}
And here are the two entities that I'm trying to add DomainUser to: DomainGroup and LocalGroup
public class DomainGroup
{
public string Name { get; set; }
public List<DomainUser> Users { get; set; }
public List<DomainGroup> Groups { get; set; }
public string DistinguishedName { get; set; }
public int Id { get; set; }
public DomainGroup()
{
Users = new List<DomainUser>();
Groups = new List<DomainGroup>();
}
}
public class LocalGroup
{
public string Name { get; set; }
public int Id { get; set; }
public string DisplayName { get; set; }
public string Comment { get; set; }
public List<LocalUser> LocalUsers { get; set; }
public List<DomainUser> DomainUsers { get; set; }
public List<DomainGroup> DomainGroups { get; set; }
public List<LocalGroup> LocalGroups { get; set; }
public LocalGroup()
{
LocalUsers = new List<LocalUser>();
LocalGroups = new List<LocalGroup>();
DomainUsers = new List<DomainUser>();
DomainGroups = new List<DomainGroup>();
}
}
Related
public IEnumerable<Parties> GetAll()
{
return database.Parties;
}
Works very well and the output is:
But when I Include another table by foreignkey like this:
public IEnumerable<Parties> GetAll()
{
return database.Parties.Include(i=>i.User);
}
It does not work, it returns first value of the table and nothing else,the output is :
Users.cs :
public partial class Users
{
public Users()
{
Parties = new HashSet<Parties>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string Biography { get; set; }
public string Password { get; set; }
public virtual ICollection<Parties> Parties { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
Parties.cs :
public partial class Parties
{
public Parties()
{
Image = new HashSet<Image>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime PartyDate { get; set; }
public DateTime CreatedDate { get; set; }
public int ParticipantCount { get; set; }
public int MaxParticipant { get; set; }
public string PartySplash { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool EntranceFree { get; set; }
public int? FreeParticipant { get; set; }
public int? FreeParticipantMax { get; set; }
public int UserId { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<Image> Image { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
As you can see on the 2nd picture it interrupts at first row of the table.
I have added this answer based on Vidmantas's comment. ReferenceLoopHandling should be ignored like this in startup.cs:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
I have a class PromoCard and List<PromoCard> PromoCards. Is it possible to map element of List array in Entity Model?
This is my List:
public static List<PromoCard> PromoCards = new List<PromoCard>
{
new PromoCard()
{
Id = 1,
Crystal = 4500,
Price = 100
},
new PromoCard()
{
Id = 2,
Crystal = 24000,
Price = 500
},
new PromoCard()
{
Id = 3,
Crystal = 50000,
Price = 1000
},
};
public class PromoCard
{
[Key]
public int Id { get; set; }
public int Crystal { get; set; }
public int Price { get; set; }
}
And this is my model:
public class BonusCard
{
[Key]
public int Id { get; set; }
public string User_id { get; set; }
[ForeignKey("User_id")]
public virtual ApplicationUser User { get; set; }
public int PromoCard_id { get; set; }
// is there way to link
[ForeignKey("PromoCard_id")]
public virtual PromoCard PromoCard { get; set; }
}
All I had to was change the getter of PromoCard property and put NotMapped Annotation on it
public class BonusCard
{
[Key]
public int Id { get; set; }
public string User_id { get; set; }
[ForeignKey("User_id")]
public virtual ApplicationUser User { get; set; }
public string Code { get; set; }
public DateTime CreationDate { get; set; } = (DateTime)SqlDateTime.MinValue;
public DateTime UsageDate { get; set; } = (DateTime)SqlDateTime.MinValue;
public int? Player_id { get; set; } = null;
[ForeignKey("Player_id")]
public virtual Player Player { get; set; }
public int PromoCard_id { get; set; }
[NotMapped]
public PromoCard PromoCard { get { return PromoCards[PromoCard_id]; } set { } }
}
I am creating ViewModels for my entities. The FirmViewModel contains two list collections called Addressess and Websites. I have also created viewmodels for Addresses and Websites. At the moment in the controller code, I am getting trouble assigning Addresses and Wesbite collections
of the Firm Entity to FirmViewModels Addresses and Websites collection. Its says cant cast it implicitly. This is the line in the controller that it complains Addresses = firm.Addresses; How do aassign
Systems.Collections.Generic.ICollection<Manager.Model.Address> to Systems.Collections.Generic.ICollection<Manager.WebUI.ViewModels.AddressViewModel>
NewFirmViewModel
public class NewFirmViewModel
{
public int FirmId { get; set; }
public string FirmName { get; set;}
public Nullable<DateTime> DateFounded { get; set; }
public ICollection<AddressViewModel> Addresses { get; set; }
public ICollection<WebsiteViewModel> Websites { get; set; }
public bool hasIntralinks { get; set; }
}
AddressViewModel
public class AddressViewModel
{
public int AddressId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Phone { get; set; }
public bool IsHeadOffice { get; set; }
public int FirmId { get; set; }
}
WebsiteViewModel
public class WebsiteViewModel
{
private int FirmWebsiteId { get; set; }
private string WebsiteUrl { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int FirmId { get; set; }
}
Entities - Firm
public class FIRM: Entity,IHasAUMs<FIRM_AUM>
{
public FIRM()
{
//this.FIRM_PERSON = new HashSet<FIRM_PERSON>();
this.MANAGERSTRATEGies = new HashSet<MANAGERSTRATEGY>();
this.FIRM_ACTIVITY = new HashSet<FIRM_ACTIVITY>();
this.FIRM_AUMs = new HashSet<FIRM_AUM>();
this.FIRM_REGISTRATION = new HashSet<FIRM_REGISTRATION>();
//this.ACTIVITies = new HashSet<ACTIVITY>();
Addresses = new HashSet<ADDRESS>();
//People = new HashSet<PERSON>();
// Websites = new HashSet<FIRM_WEBSITE>();
}
//public decimal ID { get; set; }
//
//
//
//
public string NAME { get; set; }
public string SHORT_NAME { get; set; }
public string ALTERNATE_NAME { get; set; }
public string WEBSITE { get; set; }
public string WEBSITE_USERNAME { get; set; }
public string WEBSITE_PASSWORD { get; set; }
public bool? INTRALINKS_FIRM { get; set; }
public string NOTES_TEXT { get; set; }
public string NOTES_HTML { get; set; }
public string HISTORY_TEXT { get; set; }
public string HISTORY_HTML { get; set; }
public string HISTORY_SUM_TEXT { get; set; }
public string HISTORY_SUM_HTML { get; set; }
public Nullable<decimal> OLD_ORG_REF { get; set; }
public Nullable<decimal> SOURCE_ID { get; set; }
[DisplayFormat(DataFormatString = PermalConstants.DateFormat)]
public Nullable<DateTime> DATE_FOUNDED { get; set; }
public virtual ICollection<ADDRESS> Addresses { get; set; }
// public ICollection<FIRM_WEBSITE> Websites { get; set; }
// public ICollection<PERSON> People { get; set; }
//public SOURCE SOURCE { get; set; }
// public ICollection<FIRM_PERSON> FIRM_PERSON { get; set; }
public ICollection<MANAGERSTRATEGY> MANAGERSTRATEGies { get; set; }
public ICollection<FIRM_ACTIVITY> FIRM_ACTIVITY { get; set; }
public ICollection<FIRM_REGISTRATION> FIRM_REGISTRATION { get; set; }
//public ICollection<ACTIVITY> ACTIVITies { get; set; }
public ICollection<FIRM_WEBSITE> Websites { get; set; }
public Nullable<int> KEY_CONTACT_ID { get; set; }
[NotMapped]
public ICollection<FIRM_AUM> AUMs
{
get
{
return this.FIRM_AUMs;
}
}
public ICollection<FIRM_AUM> FIRM_AUMs { get; set; }
}
ADDRESS
public class ADDRESS : Entity
{
public ADDRESS()
{
// DATE_CREATED = DateTime.Now;
}
public string LINE1 { get; set; }
public string LINE2 { get; set; }
public string LINE3 { get; set; }
public int CITY_ID { get; set; }
public string POSTAL_CODE { get; set; }
public string SWITCHBOARD_INT { get; set; }
public string NOTES { get; set; }
public int? OLD_ADDRESS_REF { get; set; }
public int? SOURCE_ID { get; set; }
public int FIRM_ID { get; set; }
[ForeignKey("FIRM_ID")]
public FIRM FIRM { get; set; }
[ForeignKey("CITY_ID")]
public CITY City { get; set; }
public ICollection<PERSON> People { get; set; }
// public SOURCE SOURCE { get; set; }
public bool IS_HEAD_OFFICE { get; set; }
[NotMapped]
public string AddressBlurb
{
get
{
return string.Join(",", new[] { LINE1, LINE2, City != null ? City.NAME : "", City != null && City.Country != null ? City.Country.NAME : "" }.Where(x => !string.IsNullOrEmpty(x)));
}
}
}
FIRM_WEBSITE
public class FIRM_WEBSITE : Entity
{
public FIRM_WEBSITE()
{
}
private string _WEBSITE_URL;
public string WEBSITE_URL
{
get
{
if (string.IsNullOrEmpty(_WEBSITE_URL))
return _WEBSITE_URL;
try
{
var ubuilder = new System.UriBuilder(_WEBSITE_URL ?? "");
return ubuilder.Uri.AbsoluteUri;
}
catch (UriFormatException ex)
{
return _WEBSITE_URL;
}
}
set { _WEBSITE_URL = value; }
}
public string USERNAME { get; set; }
public string PASSWORD { get; set; }
public int FIRM_ID { get; set; }
[ForeignKey("FIRM_ID")]
public FIRM FIRM { get; set; }
}
FirmController
public class FirmController : ApiControllerBase
{
[HttpGet]
[Route("api/Firm/{id}")]
public IHttpActionResult Details(int id)
{
var viewModel = GetFirmViewModel(id);
return Ok(viewModel);
}
private NewFirmViewModel GetFirmViewModel(int id)
{
var firmSvc = GetService<FIRM>();
var firm = firmSvc.GetWithIncludes(id, f => f.Addresses, f => f.Websites);
var firmVm = new NewFirmViewModel()
{
FirmId = firm.ID,
FirmName = firm.NAME,
DateFounded = firm.DATE_FOUNDED,
Addresses = firm.Addresses;
};
}
public virtual T GetWithIncludes(int id, params Expression<Func<T, object>>[] paths)
{
try
{
using (new TimedLogger(_perfLogger, GetCompletedText("GetWithIncludes"), typeof(T).Name))
{
return Authorize(_repo.GetWithIncludes(id, paths), AuthAccessLevel.Read);
}
}
catch (Exception ex) { Log(ex); throw; }
}
I am trying to map a model to a view, but I receive the error above when I am trying to display all my elements, since Automapper doesn't recognize the IEnumerable I think. I receive the error when I am trying to map FixedAssets to FixedAssetsView and FixedAssetsView to FixedAssets.
Here are the objects I am trying to map:
FixedAssets
public class FixedAssets : IEntityBase
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<Category> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set;
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
public FixedAssets()
{
this.category = new HashSet<Category>();
}
}
FixedAssetsView
public class FixedAssetsView
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<CategoryView> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set; }
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
}
Category
public class Category : IEntityBase
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssets> fixedasset { get; set; }
public Category()
{
this.fixedasset = new HashSet<FixedAssets>();
}
}
CategoryView
public class CategoryView
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssetsView> fixedasset { get; set; }
}
Automapper configuration
Mapper.Initialize(x =>
{
x.CreateMap<FixedAssets, FixedAssetsView>();
x.CreateMap<FixedAssetsView, FixedAssets>();
x.CreateMap<Category, CategoryView>();
x.CreateMap<CategoryView, Category>();
});
I believe you need a .ForMember in your Mapper initialization.
eg:
Mapper.CreateMap<IEnumerable<Source>, IEnumerable<Target>>()
.ForMember(f => f, mp => mp.MapFrom(
mfrom => mfrom.Select(s => AutoMapper.Mapper.Map(s, new Target())
)
);
I have a class with nested subclasses:
public class listDevicesModel
{
public int totalCount { get; set; }
public Messages messages { get; set; }
public Devices devices { get; set; }
public class Entry
{
public string key { get; set; }
public object value { get; set; }
}
public class Detail
{
public List<Entry> entry { get; set; }
}
public class Devices
{
public List<Device> device { get; set; }
}
public class Device
{
public string #id { get; set; }
public string uuid { get; set; }
public string principal { get; set; }
public int blockReason { get; set; }
public int clientId { get; set; }
public string comment { get; set; }
public int compliance { get; set; }
public int countryCode { get; set; }
public int countryId { get; set; }
public string countryName { get; set; }
public string createdAt { get; set; }
public string currentPhoneNumber { get; set; }
public List<Detail> details { get; set; }
public int deviceCount { get; set; }
public string easLastSyncAttempt { get; set; }
public string easUuid { get; set; }
public string emailAddress { get; set; }
public string emailDomain { get; set; }
public bool employeeOwned { get; set; }
public string homeOperator { get; set; }
public int languageCountryId { get; set; }
public int languageId { get; set; }
public string lastConnectedAt { get; set; }
public string manufacturer { get; set; }
public bool mdmManaged { get; set; }
public int mdmProfileUrlId { get; set; }
public string model { get; set; }
public string name { get; set; }
public bool notifyUser { get; set; }
public string #operator { get; set; }
public int operatorId { get; set; }
public string platform { get; set; }
public string platformType { get; set; }
public int quarantinedStatus { get; set; }
public int regCount { get; set; }
public string regType { get; set; }
public string registeredAt { get; set; }
public string status { get; set; }
public int statusCode { get; set; }
public string userDisplayName { get; set; }
public string userFirstName { get; set; }
public string userLastName { get; set; }
public int userSource { get; set; }
public string userUUID { get; set; }
public int wipeReason { get; set; }
}
}
In my MVC razor view i try to access the data:
#model PostenNorge.Models.JsonObjectModels.listDevicesModel
<b>#Model.messages.message</b>
<br />
<br />
<ul>
#foreach(Device d in Model.devices.device)
{
<li>#d.name - #d.uuid - #d.currentPhoneNumber</li>
}
</ul>
On Device in the foreach i get "The type or namespace name "Device" could not be found".
How can i access the nested class types in my view?
You need to specify the nested name:
#foreach(listDevicesModel.Device d in Model.devices.device)
Or use implicit typing:
#foreach(var d in Model.devices.device)
Personally I'd avoid using nested classes here anyway, unless you really have to. Even if you do really have to, I'd rename the top-level class to follow normal naming conventions, i.e. make it start with a capital letter.