I have two models in the database in a C# project looking like this:
public Company
{
{other props... }
public string Account{ get; set; }
// This is the prop I want from the Account with Account.Account == Company.Account
public int BudgetEntryType { get; set; }
}
public Account
{
public string Account{ get; set; }
public int BudgetEntryType { get; set; }
}
The value of Company.BudgetEntryType is defined in Account.BudgetEntryType, and is dependent on the value of Company.BudgetEntryType.
Is there a way of doing so? So the Company.BudgetEntryType is a reference to the Account.BudgetEntryType.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Account
{
public int Id { get; set; }
public int BudgetEntryType { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
public class ApplicationContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Account> Accounts { get; set; }
//other code
}
//-----using
Company company = new Company { Name = "Samsung" };
db.Companies.Add(company);
Account account = new Account { Company = company, BudgetEntryType = 2 };
db.Accounts.Add(account);
db.SaveChanges();
Related
I have in database two tables: product, supplier
I want the entity framework to define the supplier of each product
I am getting data successfully for two tables but the supplier in the product table is null.
Also, the products collection in the supplier table is null.
this is my product class:
public class Product
{
public int id { get; set; }
[Column("Productname", TypeName = "ntext")]
public string Name { get; set; }
public decimal UnitPrice { get; set; }
public bool isDiscounted { get; set; }
public int quantity { get; set; }
public int SupplierId { get; set; }
[ForeignKey("SupplierId")]
public Supplier supplier { get; set; }
}
this is the class of supplier:
public class Supplier
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string city { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string Fax { get; set; }
public List<Product> Products { get; set; }
}
context class:
public class DbConext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbConext(DbContextOptions<DbConext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("Product");
modelBuilder.Entity<Supplier>().ToTable("Supplier");
modelBuilder.Entity<Product>().HasKey("id");
modelBuilder.Entity<Supplier>().HasKey("Id");
modelBuilder.Entity<Product>().HasOne(p => p.supplier).WithMany(s => s.Products).HasForeignKey(p => p.SupplierId);
}
}
This article might help.
You should use .Include() to load any related properties.
minimum you need is to initialize the list
public class Supplier
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string city { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string Fax { get; set; }
public List<Product> Products { get; set; }
public Supplier() {
this.Products = new List<Product>();
}
}
I working a project and i need use lazyloading i installed package and configure,query working but relationship columns returned null. How to i can use lazyloading?
Installed Microsoft.EntityFrameworkCore.Proxies(version 5.0.7)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("ConnectionString");
optionsBuilder.UseLazyLoadingProxies(true);
}
}
My Models(I make with DB First)
public partial class Customer
{
public Customer()
{
Orders = new HashSet<Order>();
}
public int CustomerId { get; set; }
public int? CompanyId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
virtual public Company Company { get; set; }
virtual public ICollection<Order> Orders { get; set; }
}
public partial class Company
{
public Company()
{
Customers = new HashSet<Customer>();
}
public int CompanyId { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
Used Method:
public List<Customer> GetCustomers()
{
using (dbContext context = new dbContext())
{
return context.Customers.ToList();
}
}
According to the documentation, lazy loading should be implemented in this way
Install Microsoft.EntityFrameworkCore.Abstractions package too and change the implementation:
public partial class Customer
{
private ICollection<Orders> _orders;
public Customer()
{
Orders = new HashSet<Order>();
}
public Customer(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
public int CustomerId { get; set; }
public int? CompanyId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
virtual public Company Company { get; set; }
public ICollection<Order> Orders
{
get => LazyLoader.Load(this, ref _orders);
set => _orders = value;
}
}
And after iterating on orders data will be fetched
using(var db = new YourContext())
{
var customers = db.Customers.ToList();
foreach(var customer in customers )
{
Console.WriteLine($"Customer: {customer.Name} {customer .LastName}");
foreach(var order in customer.Ortders) // lazy loading initiated
{
Console.WriteLine($"\t{order.Id}");
}
}
}
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>();
}
}
I have an ASP.NET MVC project supporting multiple languages.
the tables (User,Gender,GenderTranslate) had nested inheritance
User inherit from Gender and Gender inherit from GenderTranslate
I have these tables
User table :
public partial class User
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> GenderID { get; set; }
public virtual Gender Gender { get; set; }
}
and Gender table:
public partial class Gender
{
public Gender()
{
this.GenderTranslates = new HashSet<GenderTranslate>();
this.Users = new HashSet<User>();
}
public int Id { get; set; }
public string Icon { get; set; }
public string Value { get; set; }
public virtual ICollection<GenderTranslate> GenderTranslates { get; set; }
public virtual ICollection<User> Users { get; set; }
}
and Language table:
public partial class Lang
{
public Lang()
{
this.GenderTranslates = new HashSet<GenderTranslate>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<GenderTranslate> GenderTranslates { get; set; }
}
and GenderTranslate table :
public partial class GenderTranslate
{
public int LangID { get; set; }
public int GenderID { get; set; }
public string Desc { get; set; }
public virtual Gender Gender { get; set; }
public virtual Lang Lang { get; set; }
}
When I get users I need to get GenderTranslate.Desc, not Gender.Value.
How can I do that using Entity Framework? Please help me
I have few Domain Models - Address, Customer, Employee, StoreLocation. Address has many to one relationship with Customerand Employee and one to one relationship with StoreLocation.
public class Address
{
public int Id;
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Address> Addresses { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public Address Address { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public IList<Address> Addresses { get; set; }
}
How to Map this relationship?. I am using ASP.NET MVC 3.0 and Entity Framework 4.1.
If you are using code-first (I think you want this, else, you have to edit your Q), the first way is the way explained below:
Entities:
public class Address {
[Key]
public int Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public virtual Customer Customer { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
public virtual Employee Employee { get; set; }
public int? CustomerId { get; set; }
public int? EmployeeId { get; set; }
}
public class Customer {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class StoreLocation {
[Key]
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public virtual Address Address { get; set; }
}
public class Employee {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
DbContext inherited class:
public class ManyOneToManyContext : DbContext {
static ManyOneToManyContext() {
Database.SetInitializer<ManyOneToManyContext>(new ManyOneToManyInitializer());
}
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<StoreLocation> StoreLocations { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<Customer>().HasMany(c => c.Addresses).WithOptional(a => a.Customer).HasForeignKey(a => a.CustomerId);
modelBuilder.Entity<StoreLocation>().HasRequired(s => s.Address).WithOptional(a => a.StoreLocation).Map(t => t.MapKey("AddressId"));
modelBuilder.Entity<Employee>().HasMany(e => e.Addresses).WithOptional(a => a.Employee).HasForeignKey(e => e.EmployeeId);
}
}
Context Initializer:
public class ManyOneToManyInitializer : DropCreateDatabaseAlways<ManyOneToManyContext> {
protected override void Seed(ManyOneToManyContext context) {
}
}
That will create the db-schema below:
Let me know if you have any questions or need clarifications on any part.