我正在制作一個網路應用程式,作為資料庫提供者,我使用 postgresql 和 Ef Core 作為 ORM。我有兩個班級:
public class Price
{
public int PriceId { get; set; }
public DateTime TimeStamp { get; set; }
public double Value { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
public class Company
{
public Company()
{
Prices = new HashSet<Price>();
}
public int CompanyId { get; set; }
public string Acronym { get; set; }
public string FullName { get; set; }
public virtual ICollection<Price> Prices { get; set; }
}
我的問題是,每當我嘗試為第一家公司添加一些記錄時:
var company = Context.Companies.FirstOrDefault(c => c.CompanyId == 1);
company.Prices.Add(new Price {Value = 123.45, TimeStamp = DateTime.Now});
然后為另一個
var company = Context.Companies.FirstOrDefault(c => c.CompanyId == 2);
company.Prices.Add(new Price {Value = 123.45, TimeStamp = DateTime.Now});
代替:
CompanyId | PriceId | TimeStamp | Value
-------------------------------------------
1 | 1 | foo | bar
1 | 2 | foo | bar
2 | 1 | foo | bar
2 | 2 | foo | bar
我得到:
CompanyId | PriceId | TimeStamp | Value
-------------------------------------------
1 | 1 | foo | bar
1 | 2 | foo | bar
2 | 3 | foo | bar
2 | 4 | foo | bar
我的 Pgadmin 4 配置:
公司表 - CompanyId 配置
價格表 - CompanyId 和 PriceId 配置
uj5u.com熱心網友回復:
你有一個正確的結果。PriceId 應該遞增,因為它是一個自動遞增的欄位。但是正在使用錯誤的演算法來添加新專案。如果您需要一起添加新公司和新價格,通常會使用此演算法。在這種情況下,它會自動為 Price 分配一個新的 CompanyId。但是在您的情況下,您根本不需要此代碼,因為它只會額外訪問 db 服務器并影響性能和網路流量。洗掉此代碼
var company =Context.Companies.FirstOrDefault(c => c.CompanyId ==1);
//and
var company = Context.Companies.FirstOrDefault(c =>public c.CompanyId ==2);
僅此而已就足夠了
Context.Prices.Add(new Price { CompanyId=1, Value = 123.45, TimeStampValue = DateTime.Now});
Context.Prices.Add(new Price { CompanyId=2, Value = 123.45, TimeStampValue = DateTime.Now});
或者更好
Context.Prices.AddRange( new Price[]
{
new Price {CompanyId=1, Value=123.45, TimeStamp= DateTime.Now},
new Price {CompanyId=2, Value=123.45, TimeStamp= DateTime.Now}
});
你有一對多的關系,但如果你需要多對多的關系,你將不得不將 Company 更改為 Price 類中的公司串列
public class Price
{
public int PriceId { get; set; }
public DateTime TimeStamp { get; set; }
public double Value { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
如果您使用的是 ef core net5 ,ef 將為您創建一個額外的表,否則您必須像這樣手動創建它
public class CompanyPrice
{
public int CompanyId {get; set;}
public int PriceId {get; set;}
public virtual Company Company {get; set;}
public virtual Price Price {get; set;}
}
uj5u.com熱心網友回復:
我也曾經遇到過這種情況。當首先使用代碼創建資料庫時,其中一個值必須是 ID。作為一個可能的解決方案,我不保證它會起作用,請移動
公共 int CompanyId { 獲取;放; }
到你的班級的頂部并修改如下:
> using System.ComponentModel.DataAnnotations;
> public class Price
> {
> [Required]
> public int CompanyId { get; set; }
> public int PriceId { get; set; }
> public DateTime TimeStamp { get; set; }
> public double Value { get; set; }
>
>
> public virtual Company Company { get; set; }
> }
希望它對你有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342837.html
標籤:C# PostgreSQL 实体框架
下一篇:如何使用方法更新文本塊
