【发布时间】:2015-03-14 19:10:24
【问题描述】:
我正在尝试实现实体框架代码优先的方法,但出现错误:
引入 FOREIGN KEY 约束 表上的“FK_dbo.StateMasters_dbo.CountryMasters_CountryRefId” 'StateMasters' 可能会导致循环或多个级联路径。指定开 DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
这是我的 EF 代码。只需在数据库中插入记录。
领域类:
public class CountryMaster
{
public CountryMaster()
{
}
[Key]
public int CountryCode { get; set; }
[ConcurrencyCheck, Required, MaxLength(50), MinLength(2)]
public string CountryName { get; set; }
public ICollection<StateMaster> States { get; set; }
public ICollection<CityMaster> Cities { get; set; }
}
public class StateMaster
{
public StateMaster()
{
}
[Key]
public int StateCode { get; set; }
public int CountryRefId { get; set; }
[ForeignKey("CountryRefId")]
public CountryMaster Country { get; set; }
[ConcurrencyCheck, Required, MaxLength(50), MinLength(2)]
public string StateName { get; set; }
// public ICollection<CityMaster> Cities { get; set; }
}
public class CityMaster
{
public CityMaster()
{
}
[Key]
public int CityCode { get; set; }
public int CountryRefId { get; set; }
[ForeignKey("CountryRefId")]
public CountryMaster Country { get; set; }
public int StateRefId { get; set; }
[ForeignKey("StateRefId")]
public StateMaster State { get; set; }
[ConcurrencyCheck, Required, MaxLength(50), MinLength(2)]
public string CityName { get; set; }
}
存储库接口:
public interface I_COUNTRY_STATE_CITYRepository:IDisposable
{
void InsertCountry(CountryMaster Country);
void SaveCountry();
}
存储库实现:
public class COUNTRY_STATE_CITYRepository : IDisposable, I_COUNTRY_STATE_CITYRepository
{
private COUNTRY_STATE_CITYContext context;
public COUNTRY_STATE_CITYRepository(COUNTRY_STATE_CITYContext context)
{
this.context = context;
}
public void InsertCountry(CountryMaster Country)
{
context.Countries.Add(Country);
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void SaveCountry()
{
context.SaveChanges();
}
}
上下文类:
public class COUNTRY_STATE_CITYContext: DbContext
{
public COUNTRY_STATE_CITYContext() : base("ConnectionString")
{ }
public DbSet<CountryMaster> Countries { get; set; }
public DbSet<StateMaster> States { get; set; }
public DbSet<CityMaster> Cities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CountryMaster>().HasMany(i => i.States).WithRequired().WillCascadeOnDelete(false);
}
}
C# 代码是简单地传递国家名称的值并插入数据库:
public partial class CheckCountryStateCity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btnAdd_Click(object sender, EventArgs e)
{
using (var ctx = new COUNTRY_STATE_CITYContext())
{
COUNTRY_STATE_CITYRepository wr = new COUNTRY_STATE_CITYRepository(ctx);
CountryMaster wt = new CountryMaster();
wt.CountryName = "ABC";
wr.InsertCountry(wt);
wr.SaveCountry();
}
}
}
【问题讨论】:
-
感谢编辑......